Replaces MVC with FastEndpoints in Lumina.Presentation.Api

This commit is contained in:
BinaryAlley committed 2024-10-23 21:34:10 +03:00
1 parent b1a20716df
commit c7b8bc2f1c
519 files changed
+15329 -8539

No files matched your search

@@ -16,11 +16,11 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.0" />
<PackageReference Include="FluentAssertions" Version="6.12.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Include="xunit" Version="2.9.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -35,7 +35,7 @@ public class BookJsonConverter : JsonConverter<Book>
{
JsonElement root = doc.RootElement;
Guid id = root.GetProperty("id").GetProperty("value").GetGuid();
Guid id = root.GetProperty("id").GetGuid();
DateTime created = root.GetProperty("created").GetDateTime();
WrittenContentMetadata metadata = DeserializeMetadata(root.GetProperty("metadata"));
BookFormat? format = null;
@@ -108,7 +108,7 @@ public class BookJsonConverter : JsonConverter<Book>
/// </summary>
/// <param name="element">The JSON element containing the metadata.</param>
/// <returns>The deserialized <see cref="WrittenContentMetadata"/>.</returns>
private WrittenContentMetadata DeserializeMetadata(JsonElement element)
private static WrittenContentMetadata DeserializeMetadata(JsonElement element)
{
string? title = element.GetProperty("title").GetString();
string? originalTitle = element.GetProperty("originalTitle").GetString();
@@ -146,9 +146,9 @@ public class BookJsonConverter : JsonConverter<Book>
/// </summary>
/// <param name="element">The JSON element containing the release info.</param>
/// <returns>The deserialized <see cref="ReleaseInfo"/>.</returns>
private ReleaseInfo DeserializeReleaseInfo(JsonElement element)
private static ReleaseInfo DeserializeReleaseInfo(JsonElement element)
{
DateOnly? originalReleaseDate = element.TryGetProperty("originalReleaseDate", out JsonElement ordElement) ?
DateOnly? originalReleaseDate = element.TryGetProperty("originalReleaseDate", out JsonElement ordElement) && ordElement.ValueKind != JsonValueKind.Null ?
DateOnly.Parse(ordElement.GetString()!) : (DateOnly?)null;
int? originalReleaseYear = element.TryGetProperty("originalReleaseYear", out JsonElement oryElement) && oryElement.ValueKind == JsonValueKind.Number
? oryElement.GetInt32() : (int?)null;
@@ -180,7 +180,7 @@ public class BookJsonConverter : JsonConverter<Book>
/// </summary>
/// <param name="element">The JSON element containing the genres.</param>
/// <returns>The deserialized list of <see cref="Genre"/>.</returns>
private List<Genre> DeserializeGenres(JsonElement element)
private static List<Genre> DeserializeGenres(JsonElement element)
{
return element.EnumerateArray()
.Select(g => Genre.Create(g.GetProperty("name").GetString()!).Value)
@@ -192,7 +192,7 @@ public class BookJsonConverter : JsonConverter<Book>
/// </summary>
/// <param name="element">The JSON element containing the tags.</param>
/// <returns>The deserialized list of <see cref="Tag"/>.</returns>
private List<Tag> DeserializeTags(JsonElement element)
private static List<Tag> DeserializeTags(JsonElement element)
{
return element.EnumerateArray()
.Select(t => Tag.Create(t.GetProperty("name").GetString()!).Value)
@@ -204,7 +204,7 @@ public class BookJsonConverter : JsonConverter<Book>
/// </summary>
/// <param name="element">The JSON element containing the language info.</param>
/// <returns>The deserialized <see cref="LanguageInfo"/>.</returns>
private LanguageInfo? DeserializeLanguageInfo(JsonElement element)
private static LanguageInfo? DeserializeLanguageInfo(JsonElement element)
{
if (element.ValueKind != JsonValueKind.Null)
{
@@ -231,7 +231,7 @@ public class BookJsonConverter : JsonConverter<Book>
/// </summary>
/// <param name="element">The JSON element containing the book series.</param>
/// <returns>The deserialized <see cref="BookSeries"/>.</returns>
private BookSeries DeserializeBookSeries(JsonElement element)
private static BookSeries DeserializeBookSeries(JsonElement element)
{
// TODO: implement when book series are implemented
return null!;
@@ -242,7 +242,7 @@ public class BookJsonConverter : JsonConverter<Book>
/// </summary>
/// <param name="element">The JSON element containing the ISBNs.</param>
/// <returns>The deserialized list of <see cref="Isbn"/>.</returns>
private List<Isbn> DeserializeIsbns(JsonElement element)
private static List<Isbn> DeserializeIsbns(JsonElement element)
{
return element.EnumerateArray()
.Select(i => Isbn.Create(i.GetProperty("value").GetString()!,
@@ -255,7 +255,7 @@ public class BookJsonConverter : JsonConverter<Book>
/// </summary>
/// <param name="element">The JSON element containing the contributor IDs.</param>
/// <returns>The deserialized list of <see cref="MediaContributorId"/>.</returns>
private List<MediaContributorId> DeserializeContributorIds(JsonElement element)
private static List<MediaContributorId> DeserializeContributorIds(JsonElement element)
{
// TODO: implement when contributors are implemented
return [];
@@ -266,7 +266,7 @@ public class BookJsonConverter : JsonConverter<Book>
/// </summary>
/// <param name="element">The JSON element containing the ratings.</param>
/// <returns>The deserialized list of <see cref="BookRating"/>.</returns>
private List<BookRating> DeserializeRatings(JsonElement element)
private static List<BookRating> DeserializeRatings(JsonElement element)
{
return element.EnumerateArray()
.Select(r => BookRating.Create(
@@ -8,8 +8,6 @@ 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;
@@ -1,639 +0,0 @@
#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>
{
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);
/// <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();
}
[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();
}
}
}
@@ -1,329 +0,0 @@
#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>
{
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);
/// <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();
}
[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();
}
}
}
@@ -1,634 +0,0 @@
#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>
{
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);
/// <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();
}
[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>();
}
}
@@ -1,130 +0,0 @@
#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>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly string _testImagePath;
/// <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;
}
[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>();
}
}
@@ -0,0 +1,204 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories;
/// <summary>
/// Contains integration tests for the <see cref="GetDirectoriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesEndpointTests : IClassFixture<LuminaApiFactory>
{
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);
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDirectoriesEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetDirectories_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoDirectories()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<DirectoryResponse>? directories = JsonSerializer.Deserialize<List<DirectoryResponse>>(content, _jsonOptions);
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 = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<DirectoryResponse>? directories = JsonSerializer.Deserialize<List<DirectoryResponse>>(content, _jsonOptions);
directories.Should().NotBeNull();
directories!.Should().NotBeEmpty();
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
DirectoryResponse firstDirectory = directories!.First();
firstDirectory.Name.Should().Be((s_isLinux ? "." : string.Empty) + "NestedDirectory_2");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "NestedDirectory_2" + System.IO.Path.DirectorySeparatorChar));
directories!.Count.Should().Be(1); // only directories
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult()
{
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
problemDetails["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directories");
problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directories");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel(); // Cancel the token immediately
await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -0,0 +1,411 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories;
/// <summary>
/// Contains integration tests for the <see cref="GetDirectoryTreeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeEndpointTests : IClassFixture<LuminaApiFactory>
{
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);
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDirectoryTreeEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndIncludeFilesAndNotIncludeHiddenElements_ShouldReturnDirectoryTreeWithFilesAndNotHiddenElements()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
bool includeFiles = true;
bool includeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
treeNodes.Should().NotBeNull();
treeNodes!.Should().NotBeEmpty();
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it!
pathSegments = ["/", .. pathSegments];
// recursively validate the tree structure
void ValidateNode(FileSystemTreeNodeResponse node, int depth)
{
// ensure the current node's name and path match the expected segment
string expectedSegment = pathSegments[depth];
if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':'
&& !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedSegment += System.IO.Path.DirectorySeparatorChar;
node.Name.Should().Be(expectedSegment);
string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1));
if (expectedPath.StartsWith("//"))
expectedPath = expectedPath[1..];
if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedPath += System.IO.Path.DirectorySeparatorChar;
node.Path.Should().EndWith(expectedPath);
// if the node is a drive or directory, check its children recursively
if (node.ItemType is FileSystemItemType.Root or FileSystemItemType.Directory)
{
node.Children.Should().NotBeNull();
foreach (FileSystemTreeNodeResponse childNode in node.Children)
{
if (childNode.ItemType != FileSystemItemType.File) // go deeper one level, if the iterated node's children is also a directory
ValidateNode(childNode, depth + 1);
else if (childNode.ItemType is FileSystemItemType.File)
{
childNode.Children.Should().BeEmpty(); // files should not have children
childNode.Name.Should().Be("TestFile_2.txt");
}
}
}
}
FileSystemTreeNodeResponse rootNode = treeNodes!.First();
ValidateNode(rootNode, 0);
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndIncludeFilesAndWithIncludeHiddenElements_ShouldReturnDirectoryTreeWithFilesAndHiddenElements()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
bool includeFiles = true;
bool includeHiddenElements = true;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
treeNodes.Should().NotBeNull();
treeNodes!.Should().NotBeEmpty();
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it!
pathSegments = ["/", .. pathSegments];
// recursively validate the tree structure
void ValidateNode(FileSystemTreeNodeResponse node, int depth)
{
// ensure the current node's name and path match the expected segment
string expectedSegment = pathSegments[depth];
if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':'
&& !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedSegment += System.IO.Path.DirectorySeparatorChar;
node.Name.Should().Be(expectedSegment);
string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1));
if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedPath += System.IO.Path.DirectorySeparatorChar;
if (expectedPath.StartsWith("//"))
expectedPath = expectedPath[1..];
node.Path.Should().EndWith(expectedPath);
// if the node is a drive or directory, check its children recursively
if (node.ItemType is FileSystemItemType.Root or FileSystemItemType.Directory)
{
node.Children.Should().NotBeNull();
foreach (FileSystemTreeNodeResponse childNode in node.Children)
{
if (childNode.ItemType != FileSystemItemType.File) // go deeper one level, if the iterated node's children is also a directory
ValidateNode(childNode, depth + 1);
else if (childNode.ItemType is FileSystemItemType.File)
{
childNode.Children.Should().BeEmpty(); // files should not have children
childNode.Name.Should().BeOneOf((s_isLinux ? "." : string.Empty) + "TestFile_1.txt", "TestFile_2.txt");
}
}
}
}
FileSystemTreeNodeResponse rootNode = treeNodes!.First();
ValidateNode(rootNode, 0);
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeFilesAndNotIncludeHiddenElements_ShouldReturnDirectoryTreeWithoutFiles()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
bool includeFiles = false;
bool includeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
treeNodes.Should().NotBeNull();
treeNodes!.Should().NotBeEmpty();
// there should not be a File node
treeNodes.Should().AllSatisfy(node => node.ItemType.Should().BeOneOf(FileSystemItemType.Directory, FileSystemItemType.Root));
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it!
pathSegments = ["/", .. pathSegments];
// recursively validate the tree structure
void ValidateNode(FileSystemTreeNodeResponse node, int depth)
{
// ensure the current node's name and path match the expected segment
string expectedSegment = pathSegments[depth];
if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':'
&& !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedSegment += System.IO.Path.DirectorySeparatorChar;
node.Name.Should().Be(expectedSegment);
string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1));
if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedPath += System.IO.Path.DirectorySeparatorChar;
if (expectedPath.StartsWith("//"))
expectedPath = expectedPath[1..];
node.Path.Should().EndWith(expectedPath);
node.Children.Should().NotBeNull();
foreach (FileSystemTreeNodeResponse childNode in node.Children)
ValidateNode(childNode, depth + 1);
}
FileSystemTreeNodeResponse rootNode = treeNodes!.First();
ValidateNode(rootNode, 0);
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeFilesAndIncludeHiddenElements_ShouldReturnDirectoryTreeWithoutFiles()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
bool includeFiles = false;
bool includeHiddenElements = true;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
treeNodes.Should().NotBeNull();
treeNodes!.Should().NotBeEmpty();
// there should not be a File node
treeNodes.Should().AllSatisfy(node => node.ItemType.Should().BeOneOf(FileSystemItemType.Directory, FileSystemItemType.Root));
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
if (s_isLinux) // on UNIX, the leading slash is considered "the drive", the root location - add it!
pathSegments = ["/", .. pathSegments];
// recursively validate the tree structure
void ValidateNode(FileSystemTreeNodeResponse node, int depth)
{
// ensure the current node's name and path match the expected segment
string expectedSegment = pathSegments[depth];
if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':'
&& !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedSegment += System.IO.Path.DirectorySeparatorChar;
node.Name.Should().Be(expectedSegment);
string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1));
if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedPath += System.IO.Path.DirectorySeparatorChar;
if (expectedPath.StartsWith("//"))
expectedPath = expectedPath[1..];
node.Path.Should().EndWith(expectedPath);
node.Children.Should().NotBeNull();
foreach (FileSystemTreeNodeResponse childNode in node.Children)
ValidateNode(childNode, depth + 1);
}
FileSystemTreeNodeResponse rootNode = treeNodes!.First();
ValidateNode(rootNode, 0);
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnValidationProblemResult()
{
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
bool includeFiles = false;
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directory-tree");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
bool includeFiles = false;
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-directory-tree");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeFiles = false;
bool includeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeFiles = false;
bool includeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel(); // Cancel the token immediately
await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -0,0 +1,247 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories;
/// <summary>
/// Contains integration tests for the <see cref="GetTreeDirectoriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesEndpointTests : IClassFixture<LuminaApiFactory>
{
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);
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTreeDirectoriesEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeDirectoriesWithoutHiddenElements()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
treeNodes.Should().NotBeNull();
treeNodes!.Should().NotBeEmpty();
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
FileSystemTreeNodeResponse firstNode = treeNodes!.First();
firstNode.Name.Should().Be("NestedDirectory_3");
firstNode.Path.Should().Be(System.IO.Path.Combine(testPath, "NestedDirectory_3" + System.IO.Path.DirectorySeparatorChar));
firstNode.ItemType.Should().Be(FileSystemItemType.Directory);
treeNodes.Should().AllSatisfy(n => n.ItemType.Should().Be(FileSystemItemType.Directory));
treeNodes!.Count.Should().Be(1); // only directories
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnNoTreeDirectories()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
treeNodes.Should().NotBeNull();
treeNodes!.Should().BeEmpty();
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeDirectoriesWithHiddenElements()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
treeNodes.Should().NotBeNull();
treeNodes!.Should().NotBeEmpty();
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
FileSystemTreeNodeResponse firstNode = treeNodes!.First();
firstNode.Name.Should().Be((s_isLinux ? "." : string.Empty) + "NestedDirectory_2");
firstNode.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isLinux ? "." : string.Empty) + "NestedDirectory_2" + System.IO.Path.DirectorySeparatorChar));
firstNode.ItemType.Should().Be(FileSystemItemType.Directory);
treeNodes.Should().AllSatisfy(n => n.ItemType.Should().Be(FileSystemItemType.Directory));
treeNodes!.Count.Should().Be(1); // only directories
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult()
{
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
problemDetails["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-tree-directories");
problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-tree-directories");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel(); // Cancel the token immediately
await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -1,28 +1,26 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
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;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Drives;
/// <summary>
/// Contains integration tests for the <see cref="DrivesController"/> class.
/// Contains integration tests for the <see cref="GetDrivesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DrivesControllerTests : IClassFixture<LuminaApiFactory>
public class GetDrivesEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
@@ -34,17 +32,16 @@ public class DrivesControllerTests : IClassFixture<LuminaApiFactory>
private static readonly bool s_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
/// <summary>
/// Initializes a new instance of the <see cref="DrivesControllerTests"/> class.
/// Initializes a new instance of the <see cref="GetDrivesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DrivesControllerTests(LuminaApiFactory apiFactory)
public GetDrivesEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetDrives_WhenCalled_ShouldReturnDrives()
public async Task ExecuteAsync_WhenCalled_ShouldReturnDrives()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/drives/get-drives");
@@ -53,27 +50,16 @@ public class DrivesControllerTests : IClassFixture<LuminaApiFactory>
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
List<FileSystemTreeNodeResponse> drives = [];
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? drives = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
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();
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);
drives!.Count.Should().BeGreaterThanOrEqualTo(1);
}
}
@@ -1,14 +1,10 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
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;
@@ -17,13 +13,13 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.FileSystem;
/// <summary>
/// Contains integration tests for the <see cref="FileSystemController"/> class.
/// Contains integration tests for the <see cref="GetTypeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemControllerTests : IClassFixture<LuminaApiFactory>
public class GetTypeEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
@@ -34,19 +30,19 @@ public class FileSystemControllerTests : IClassFixture<LuminaApiFactory>
};
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemControllerTests"/> class.
/// Initializes a new instance of the <see cref="GetTypeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public FileSystemControllerTests(LuminaApiFactory apiFactory)
public GetTypeEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetType_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse()
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithFileSystemTypeResponse()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1.0/file-system/get-type");
HttpResponseMessage response = await _client.GetAsync("/api/v1/file-system/get-type");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -57,11 +53,11 @@ public class FileSystemControllerTests : IClassFixture<LuminaApiFactory>
}
[Fact]
public async Task GetType_WhenCalledMultipleTimes_ShouldReturnConsistentResults()
public async Task ExecuteAsync_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");
HttpResponseMessage response1 = await _client.GetAsync("/api/v1/file-system/get-type");
HttpResponseMessage response2 = await _client.GetAsync("/api/v1/file-system/get-type");
// Assert
response1.StatusCode.Should().Be(HttpStatusCode.OK);
@@ -79,13 +75,13 @@ public class FileSystemControllerTests : IClassFixture<LuminaApiFactory>
}
[Fact]
public async Task GetType_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
public async Task ExecuteAsync_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);
Func<Task> act = async () => await _client.GetAsync("/api/v1/file-system/get-type", cts.Token);
// Assert
await act.Should().NotThrowAsync();
@@ -0,0 +1,243 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Files;
/// <summary>
/// Contains integration tests for the <see cref="GetFilesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesEndpointTests : IClassFixture<LuminaApiFactory>
{
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);
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetFilesEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnFilesWithoutHiddenElements()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
testPath = System.IO.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);
string content = await response.Content.ReadAsStringAsync();
List<FileResponse>? files = JsonSerializer.Deserialize<List<FileResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
files!.Should().NotBeEmpty();
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
FileResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be("TestFile_2.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
files!.Count.Should().Be(1); // only files
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoFiles()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
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);
string content = await response.Content.ReadAsStringAsync();
List<FileResponse>? files = JsonSerializer.Deserialize<List<FileResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
FileResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be("TestFile_2.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnFilesWithHiddenElements()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
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);
string content = await response.Content.ReadAsStringAsync();
List<FileResponse>? files = JsonSerializer.Deserialize<List<FileResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
files!.Should().NotBeEmpty();
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
FileResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be((s_isLinux ? "." : string.Empty) + "TestFile_1.txt");
firstDirectory.Path.Should().Be(System.IO.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(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
files!.Count.Should().Be(2);
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult()
{
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
problemDetails["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-files");
problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-files");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel(); // Cancel the token immediately
await _client.GetAsync($"/api/v1/files/get-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -0,0 +1,243 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Files;
/// <summary>
/// Contains integration tests for the <see cref="GetTreeFilesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesEndpointTests : IClassFixture<LuminaApiFactory>
{
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);
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTreeFilesEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeHiddenElements_ShouldReturnTreeFilesWithoutHiddenElements()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
testPath = System.IO.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);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? files = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
files!.Should().NotBeEmpty();
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
FileSystemTreeNodeResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be("TestFile_2.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
files!.Count.Should().Be(1); // only files
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndHiddenChildrenAndNotIncludeHiddenElements_ShouldReturnNoTreeFiles()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
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);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? files = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
FileSystemTreeNodeResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be("TestFile_2.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndWithIncludeHiddenElements_ShouldReturnTreeFilesWithHiddenElements()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath;
testPath = System.IO.Path.GetDirectoryName(testPath) ?? testPath; // two levels to get to the element that has a hidden element as child
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);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? files = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
files.Should().NotBeNull();
files!.Should().NotBeEmpty();
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
FileSystemTreeNodeResponse firstDirectory = files!.First();
firstDirectory.Name.Should().Be((s_isLinux ? "." : string.Empty) + "TestFile_1.txt");
firstDirectory.Path.Should().Be(System.IO.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(System.IO.Path.Combine(testPath, "TestFile_2.txt"));
files!.Count.Should().Be(2);
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult()
{
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
problemDetails["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-tree-files");
problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/files/get-tree-files");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
bool includeHiddenElements = true;
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel(); // Cancel the token immediately
await _client.GetAsync($"/api/v1/files/get-tree-files?path={encodedPath}&includeHiddenElements={includeHiddenElements}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -5,7 +5,7 @@ using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
/// <summary>
/// Fixture class for creating and managing a file system structure for integration testing purposes.
@@ -21,7 +21,7 @@ public class FileSystemStructureFixture
/// </summary>
public FileSystemStructureFixture()
{
_rootPath = Path.Combine(AppContext.BaseDirectory, "TestFileSystemStructure_" + Guid.NewGuid());
_rootPath = System.IO.Path.Combine(AppContext.BaseDirectory, "TestFileSystemStructure_" + Guid.NewGuid());
}
@@ -38,13 +38,13 @@ public class FileSystemStructureFixture
for (int i = 1; i <= 3; i++)
{
// create a nested subdirectory
currentPath = Path.Combine(currentPath, $"NestedDirectory_{i}");
currentPath = System.IO.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");
string filePath = System.IO.Path.Combine(currentPath, $"TestFile_{j}.txt");
File.WriteAllText(filePath, _faker.Lorem.Paragraph());
// make the first file in each directory hidden
if (j == 1)
@@ -68,9 +68,9 @@ public class FileSystemStructureFixture
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);
string directory = System.IO.Path.GetDirectoryName(path)!;
string name = System.IO.Path.GetFileName(path);
string newPath = System.IO.Path.Combine(directory, "." + name);
if (Directory.Exists(path))
Directory.Move(path, newPath);
else if (File.Exists(path))
@@ -1,13 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
/// <summary>
/// Fixture class for the <see cref="FileSystemTreeNodeResponse"/> class.
@@ -7,7 +7,7 @@ using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement.Fixtures;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
/// <summary>
/// Fixture class for creating and managing a test image for integration testing purposes.
@@ -25,7 +25,7 @@ public class TestImageFixture : IDisposable
/// </summary>
public TestImageFixture()
{
ImagePath = Path.Combine(Path.GetTempPath(), $"TestImage_{Guid.NewGuid()}.jpg");
ImagePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"TestImage_{Guid.NewGuid()}.jpg");
CreateTestImage();
}
@@ -0,0 +1,126 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
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.Endpoints.FileSystemManagement.Path;
/// <summary>
/// Contains integration tests for the <see cref="CheckPathExistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CheckPathExistsEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithExistingPath_ShouldReturnOkResultWithExistsTrue()
{
// Arrange
string tempPath = System.IO.Path.GetTempPath();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/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 ExecuteAsync_WhenCalledWithNonExistingPath_ShouldReturnOkResultWithExistsFalse()
{
// Arrange
string nonExistingPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/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 ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnOkResultWithExistsFalse()
{
// Arrange
string path = "";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/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 ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnOkResultWithExistsFalse()
{
// Arrange
string invalidPath = "invalid:path";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/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 ExecuteAsync_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/path/check-path-exists?path={encodedPath}&includeHiddenElements=false", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
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.Endpoints.FileSystemManagement.Path;
/// <summary>
/// Contains integration tests for the <see cref="CombinePathEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CombinePathEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_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/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 ExecuteAsync_WhenCalledWithEmptyPaths_ShouldReturnValidationProblemResult()
{
// Arrange
string originalPath = "";
string newPath = "";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/combine");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
string originalPath = "/home/user";
string newPath = "documents";
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ExecuteAsync_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/path/combine?originalPath={Uri.EscapeDataString(originalPath)}&newPath={Uri.EscapeDataString(newPath)}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -0,0 +1,191 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path;
/// <summary>
/// Contains integration tests for the <see cref="GetPathParentEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentEndpointTests : IClassFixture<LuminaApiFactory>
{
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);
/// <summary>
/// Initializes a new instance of the <see cref="GetPathParentEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPathParentEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_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/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 == System.IO.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 ExecuteAsync_WhenCalledWithRootPath_ShouldReturnForbiddenResult()
{
// Arrange
string rootPath = System.IO.Path.GetPathRoot(System.IO.Path.GetTempPath())!;
string encodedPath = Uri.EscapeDataString(rootPath);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
problemDetails["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-parent");
problemDetails["detail"].GetString().Should().Be("CannotNavigateUp");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnValidationProblemResult()
{
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-parent");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-parent");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException()
{
// Arrange
string testPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "testDirectory");
string encodedPath = Uri.EscapeDataString(testPath);
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel(); // Cancel the token immediately
await _client.GetAsync($"/api/v1/path/get-path-parent?path={encodedPath}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -0,0 +1,149 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path;
/// <summary>
/// Contains integration tests for the <see cref="GetPathRootEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathRootEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPathRootEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPath_ShouldReturnOkResultWithPathSegmentResponse()
{
// Arrange
string testPath = System.IO.Path.GetTempPath();
string encodedPath = Uri.EscapeDataString(testPath);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/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 ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnValidationProblemResult()
{
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-root");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/get-path-root");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
string testPath = System.IO.Path.GetTempPath();
string encodedPath = Uri.EscapeDataString(testPath);
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/path/get-path-root?path={encodedPath}", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ExecuteAsync_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/path/get-path-root?path={encodedPath}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -0,0 +1,105 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
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.Endpoints.FileSystemManagement.Path;
/// <summary>
/// Contains integration tests for the <see cref="GetPathSeparatorEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathSeparatorEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetPathSeparatorEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPathSeparatorEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathSeparatorResponse()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/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 ExecuteAsync_WhenCalledMultipleTimes_ShouldReturnConsistentResults()
{
// Act
HttpResponseMessage response1 = await _client.GetAsync("/api/v1/path/get-path-separator");
HttpResponseMessage response2 = await _client.GetAsync("/api/v1/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 ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync("/api/v1/path/get-path-separator", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException()
{
// Arrange
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel(); // Cancel the token immediately
await _client.GetAsync("/api/v1/path/get-path-separator", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Path;
/// <summary>
/// Contains integration tests for the <see cref="SplitPathEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SplitPathEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SplitPathEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_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/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 ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string path = "";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(path)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/split");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnProblemDetails()
{
// Arrange
string path = "invalid:path";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/split?path={Uri.EscapeDataString(path)}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/path/split");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["InvalidPath"]);
}
[Fact]
public async Task ExecuteAsync_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/path/split?path={encodedPath}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
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.Endpoints.FileSystemManagement.Path;
/// <summary>
/// Contains integration tests for the <see cref="ValidatePathEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ValidatePathEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_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/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 ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnOkResultWithIsValidFalse()
{
// Arrange
string invalidPath = "invalid:path";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/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 ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnOkResultWithIsValidFalse()
{
// Arrange
string path = "";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/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 ExecuteAsync_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/path/validate?path={encodedPath}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -0,0 +1,155 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.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.Endpoints.FileSystemManagement.Thumbnails;
/// <summary>
/// Contains integration tests for the <see cref="GetThumbnailEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailEndpointTests : IClassFixture<LuminaApiFactory>, IClassFixture<TestImageFixture>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly string _testImagePath;
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
/// <param name="imageFixture">Fixture for creating and managing test images.</param>
public GetThumbnailEndpointTests(LuminaApiFactory apiFactory, TestImageFixture imageFixture)
{
_client = apiFactory.CreateClient();
_testImagePath = imageFixture.ImagePath;
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndQuality_ShouldReturnOkResultWithThumbnail()
{
// Arrange
int quality = 80;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/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 ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult()
{
// Arrange
string invalidImagePath = "/path/to/nonexistent/image.jpg";
int quality = 80;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
problemDetails["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/thumbnails/get-thumbnail");
problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string invalidImagePath = "";
int quality = 80;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(invalidImagePath)}&quality={quality}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/thumbnails/get-thumbnail");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidQuality_ShouldReturnValidationProblemResult()
{
// Arrange
int invalidQuality = -1;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={invalidQuality}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["instance"].GetString().Should().Be("/api/v1/thumbnails/get-thumbnail");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["ImageQaulityMustBeBetweenZeroAndOneHundred"]);
}
[Fact]
public async Task ExecuteAsync_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/thumbnails/get-thumbnail?path={Uri.EscapeDataString(_testImagePath)}&quality={quality}", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -1,12 +1,12 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Bogus;
using Lumina.Contracts.Entities.Common;
using Lumina.Contracts.Entities.MediaContributors;
using Lumina.Contracts.Entities.WrittenContentLibrary;
using Lumina.Contracts.Entities.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Contracts.Models.Common;
using Lumina.Contracts.Models.MediaContributors;
using Lumina.Contracts.Models.WrittenContentLibrary;
using Lumina.Contracts.Models.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System;
using System.Collections.Generic;
@@ -14,7 +14,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books.Fixtures;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.Fixtures;
/// <summary>
/// Fixture class for the <see cref="AddBookRequest"/> class.
@@ -46,8 +46,8 @@ public class AddBookRequestFixture
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
ReleaseInfoModel releaseInfo = new Faker<ReleaseInfoModel>()
.CustomInstantiator(f => new ReleaseInfoModel(
ReleaseInfoEntity releaseInfo = new Faker<ReleaseInfoEntity>()
.CustomInstantiator(f => new ReleaseInfoEntity(
default,
default,
default,
@@ -63,44 +63,44 @@ public class AddBookRequestFixture
.RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50)))
.Generate();
Faker<GenreModel> genre = new Faker<GenreModel>()
.CustomInstantiator(f => new GenreModel(
Faker<GenreEntity> genre = new Faker<GenreEntity>()
.CustomInstantiator(f => new GenreEntity(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<TagModel> tag = new Faker<TagModel>()
.CustomInstantiator(f => new TagModel(
Faker<TagEntity> tag = new Faker<TagEntity>()
.CustomInstantiator(f => new TagEntity(
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<MediaContributorRoleModel> mediaContributorRole = new Faker<MediaContributorRoleModel>()
.CustomInstantiator(f => new MediaContributorRoleModel(
Faker<MediaContributorRoleEntity> mediaContributorRole = new Faker<MediaContributorRoleEntity>()
.CustomInstantiator(f => new MediaContributorRoleEntity(
default!,
default!
))
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<MediaContributorNameModel> mediaContributorName = new Faker<MediaContributorNameModel>()
.CustomInstantiator(f => new MediaContributorNameModel(
Faker<MediaContributorNameEntity> mediaContributorName = new Faker<MediaContributorNameEntity>()
.CustomInstantiator(f => new MediaContributorNameEntity(
default!,
default!
))
.RuleFor(e => e.DisplayName, f => f.Random.String2(f.Random.Number(1, 50)))
.RuleFor(e => e.LegalName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<MediaContributorModel> mediaContributor = new Faker<MediaContributorModel>()
.CustomInstantiator(f => new MediaContributorModel(
Faker<MediaContributorEntity> mediaContributor = new Faker<MediaContributorEntity>()
.CustomInstantiator(f => new MediaContributorEntity(
default!,
default!
))
.RuleFor(e => e.Name, mediaContributorName)
.RuleFor(e => e.Role, mediaContributorRole);
Faker<BookRatingModel> rating = new Faker<BookRatingModel>()
.CustomInstantiator(f => new BookRatingModel(
Faker<BookRatingEntity> rating = new Faker<BookRatingEntity>()
.CustomInstantiator(f => new BookRatingEntity(
default,
default,
default,
@@ -111,8 +111,8 @@ public class AddBookRequestFixture
.RuleFor(e => e.Source, _fixture.Create<BookRatingSource>())
.RuleFor(e => e.VoteCount, _random.Next(1, 1000));
Faker<LanguageInfoModel> language = new Faker<LanguageInfoModel>()
.CustomInstantiator(f => new LanguageInfoModel(
Faker<LanguageInfoEntity> language = new Faker<LanguageInfoEntity>()
.CustomInstantiator(f => new LanguageInfoEntity(
default!,
default!,
default
@@ -121,8 +121,8 @@ public class AddBookRequestFixture
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<LanguageInfoModel> originalLanguage = new Faker<LanguageInfoModel>()
.CustomInstantiator(f => new LanguageInfoModel(
Faker<LanguageInfoEntity> originalLanguage = new Faker<LanguageInfoEntity>()
.CustomInstantiator(f => new LanguageInfoEntity(
default!,
default!,
default
@@ -131,8 +131,8 @@ public class AddBookRequestFixture
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
Faker<WrittenContentMetadataModel> metadata = new Faker<WrittenContentMetadataModel>()
.CustomInstantiator(f => new WrittenContentMetadataModel(
Faker<WrittenContentMetadataEntity> metadata = new Faker<WrittenContentMetadataEntity>()
.CustomInstantiator(f => new WrittenContentMetadataEntity(
default!,
default,
default,
@@ -155,8 +155,8 @@ public class AddBookRequestFixture
.RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100)))
.RuleFor(x => x.PageCount, _random.Next(100, 300));
Faker<IsbnModel> isbn = new Faker<IsbnModel>()
.CustomInstantiator(f => new IsbnModel(
Faker<IsbnEntity> isbn = new Faker<IsbnEntity>()
.CustomInstantiator(f => new IsbnEntity(
default!,
default
))
@@ -272,72 +272,4 @@ public class AddBookRequestFixture
.RuleFor(p => p.Ratings, f => rating.Generate(f.Random.Number(1, 5)))
.RuleFor(x => x.Contributors, f => mediaContributor.Generate(f.Random.Number(1, 5)));
}
private void ConfigureCustomRequestTypes()
{
int releaseYear = _random.Next(2000, 2010);
int reReleaseYear = _random.Next(2010, 2020);
_fixture.Register(() => new ReleaseInfoModel(
_faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)),
releaseYear,
_faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)),
reReleaseYear,
_fixture.Create<string>()[2..],
_fixture.Create<string?>()));
_fixture.Register(() => new GenreModel(
_fixture.Create<string>()
));
_fixture.Register(() => new TagModel(
_fixture.Create<string>()
));
_fixture.Register(() => new LanguageInfoModel(
_fixture.Create<string>(),
_fixture.Create<string>(),
_fixture.Create<string?>()
));
_fixture.Register(() => new IsbnModel(
_fixture.Create<string>(),
_fixture.Create<IsbnFormat>()
));
_fixture.Register(() => new BookRatingModel(
_fixture.Create<decimal>(),
_fixture.Create<decimal>(),
_fixture.Create<BookRatingSource?>(),
_fixture.Create<int?>()
));
_fixture.Register(() => new WrittenContentMetadataModel(
_fixture.Create<string>()[255..],
LimitStringLength(_fixture.Create<string?>(), 255),
LimitStringLength(_fixture.Create<string?>(), 2000),
_fixture.Create<ReleaseInfoModel>(),
_fixture.Create<List<GenreModel>>(),
_fixture.Create<List<TagModel>>(),
_fixture.Create<LanguageInfoModel?>(),
_fixture.Create<LanguageInfoModel?>(),
_fixture.Create<string?>(),
_fixture.Create<int?>()
));
_fixture.Register(() => new BookSeriesModel(
_fixture.Create<string>()
));
_fixture.Register(() => new MediaContributorRoleModel(
_fixture.Create<string>(),
_fixture.Create<string>()
));
_fixture.Register(() => new MediaContributorNameModel(
_fixture.Create<string>(),
_fixture.Create<string?>()
));
_fixture.Register(() => new MediaContributorModel(
_fixture.Create<MediaContributorNameModel>(),
_fixture.Create<MediaContributorRoleModel>()
));
}
private static string? LimitStringLength(string? input, int maxLength)
{
return input?.Length > maxLength ? input[..maxLength] : input;
}
}
@@ -13,7 +13,7 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books.Fixtures;
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.Fixtures;
/// <summary>
/// Fixture class for the <see cref="Book"/> domain entity.
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Contains integration tests for the <see cref="GetBooksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetBooksEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetBooks_WhenCalled_ShouldReturnBooks()
{
// Arrange
HttpResponseMessage response = await _client.GetAsync("/api/v1/books");
// Act
response.EnsureSuccessStatusCode();
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
Book[]? bookResponse = await response.Content.ReadFromJsonAsync<Book[]>(_jsonOptions);
bookResponse.Should().NotBeNull();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act
Func<Task> act = async () => await _client.GetAsync($"/api/v1/books", cts.Token);
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ExecuteAsync_WhenCancellationTokenIsCancelled_ShouldThrowTaskCanceledException()
{
// Arrange
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel(); // Cancel the token immediately
await _client.GetAsync($"/api/v1/books", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
}
@@ -17,12 +17,12 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.8" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.0" />
<PackageReference Include="FluentAssertions" Version="6.12.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.10" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Include="xunit" Version="2.9.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>