Updates to .NET 9.0

This commit is contained in:
BinaryAlley committed 2024-11-13 20:46:54 +02:00
commit acbdb0a5f8
853 files changed
+34993 -10123

No files matched your search

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
@@ -9,6 +9,13 @@
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="5.0.0-preview0011" />
<PackageReference Include="AutoFixture.Xunit2" Version="5.0.0-preview0011" />
@@ -16,12 +23,12 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.4" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0-rc.2.24473.5" />
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.5" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.35">
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.49">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
@@ -1,11 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -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(
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Fixtures;
/// <summary>
/// Provides JWT token generation functionality for testing purposes.
/// </summary>
[ExcludeFromCodeCoverage]
public class JwtFixture
{
private static readonly string s_secretKey = "test-key-thats-at-least-32-chars-long-for-jwt";
/// <summary>
/// Generates a JWT token for testing with the specified username and optional roles.
/// </summary>
/// <param name="username">The username to include in the token claims.</param>
/// <param name="roles">Optional array of roles to include in the token claims.</param>
/// <returns>A JWT token string that can be used for authentication in tests.</returns>
public static string GenerateJwtToken(string username, string[]? roles = null)
{
byte[] key = Encoding.ASCII.GetBytes(s_secretKey);
List<Claim> claims =
[
new(ClaimTypes.Name, username),
new(ClaimTypes.NameIdentifier, username)
];
if (roles?.Length > 0)
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
JwtSecurityToken token = new(
issuer: "test-issuer",
audience: "test-audience",
claims: claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
@@ -1,15 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Core.UoW;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -21,6 +24,7 @@ namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
{
private readonly SqliteConnection _connection;
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
/// <summary>
/// Initializes a new instance of the <see cref="LuminaApiFactory"/> class.
@@ -37,6 +41,22 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
/// <param name="builder">The web host builder to configure.</param>
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration((context, config) =>
{
// clear all existing configuration sources
config.Sources.Clear();
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddJsonFile($"appsettings.test.json", optional: true, reloadOnChange: true);
config.AddJsonFile("appsettings.shared.json", optional: true, reloadOnChange: true);
config.AddJsonFile($"appsettings.shared.test.json", optional: true, reloadOnChange: true);
// First add the test values directly
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
{
["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt",
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key
});
});
builder.ConfigureServices(services =>
{
// remove existing DbContext configuration
@@ -45,16 +65,30 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
services.Remove(descriptor);
// add SQLite DbContext configuration
services.AddDbContext<LuminaDbContext>(options => options.UseSqlite(_connection));
// configure JWT authentication for testing
services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "test-issuer",
ValidAudience = "test-audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("test-key-thats-at-least-32-chars-long-for-jwt"))
};
});
// build service provider and ensure database is created
ServiceProvider servicePreovider = services.BuildServiceProvider();
using (IServiceScope scope = servicePreovider.CreateScope())
{
IServiceProvider scopedServices = scope.ServiceProvider;
LuminaDbContext dbContext = scopedServices.GetRequiredService<LuminaDbContext>();
dbContext.Database.EnsureCreated();
dbContext.Database.Migrate();
}
});
}
}
/// <summary>
/// Disposes the connection to the database.
@@ -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,79 +0,0 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Contracts.Enums.FileSystem;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.FileManagement;
/// <summary>
/// Contains integration tests for the <see cref="DrivesController"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DrivesControllerTests : IClassFixture<LuminaApiFactory>
{
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="DrivesControllerTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DrivesControllerTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetDrives_WhenCalled_ShouldReturnDrives()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/drives/get-drives");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
List<FileSystemTreeNodeResponse> drives = [];
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
using (JsonDocument jsonDoc = await JsonDocument.ParseAsync(stream))
{
foreach (JsonElement element in jsonDoc.RootElement.EnumerateArray())
{
FileSystemTreeNodeResponse? drive = JsonSerializer.Deserialize<FileSystemTreeNodeResponse>(element.GetRawText(), _jsonOptions);
if (drive is not null)
drives.Add(drive);
}
}
}
drives.Should().NotBeNull();
drives.Should().NotBeEmpty();
FileSystemTreeNodeResponse firstDrive = drives.First();
firstDrive.Name.Should().Be(s_isLinux ? "/" : "C:\\");
firstDrive.Path.Should().Be(s_isLinux ? "/" : "C:\\");
firstDrive.ItemType.Should().Be(FileSystemItemType.Root);
drives.Count.Should().BeGreaterThanOrEqualTo(1);
}
}
@@ -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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
/// <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_isUnix ? "." : string.Empty) + "NestedDirectory_2");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : 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.Domain.Common.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories;
/// <summary>
/// Contains integration tests for the <see cref="GetDirectoryTreeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeEndpointTests : IClassFixture<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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDirectoryTreeEndpointTests(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_isUnix) // on UNIX, the leading slash is considered "the drive", the root location - add it!
pathSegments = ["/", .. pathSegments];
// recursively validate the tree structure
void ValidateNode(FileSystemTreeNodeResponse node, int depth)
{
// ensure the current node's name and path match the expected segment
string expectedSegment = pathSegments[depth];
if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':'
&& !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedSegment += System.IO.Path.DirectorySeparatorChar;
node.Name.Should().Be(expectedSegment);
string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1));
if (expectedPath.StartsWith("//"))
expectedPath = expectedPath[1..];
if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedPath += System.IO.Path.DirectorySeparatorChar;
node.Path.Should().EndWith(expectedPath);
// if the node is a drive or directory, check its children recursively
if (node.ItemType is FileSystemItemType.Root or FileSystemItemType.Directory)
{
node.Children.Should().NotBeNull();
foreach (FileSystemTreeNodeResponse childNode in node.Children)
{
if (childNode.ItemType != FileSystemItemType.File) // go deeper one level, if the iterated node's children is also a directory
ValidateNode(childNode, depth + 1);
else if (childNode.ItemType is FileSystemItemType.File)
{
childNode.Children.Should().BeEmpty(); // files should not have children
childNode.Name.Should().Be("TestFile_2.txt");
}
}
}
}
FileSystemTreeNodeResponse rootNode = treeNodes!.Where(node => testPath.StartsWith(node.Name)).First();
ValidateNode(rootNode, 0);
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndIncludeFilesAndWithIncludeHiddenElements_ShouldReturnDirectoryTreeWithFilesAndHiddenElements()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
bool includeFiles = true;
bool includeHiddenElements = true;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
treeNodes.Should().NotBeNull();
treeNodes!.Should().NotBeEmpty();
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
if (s_isUnix) // on UNIX, the leading slash is considered "the drive", the root location - add it!
pathSegments = ["/", .. pathSegments];
// recursively validate the tree structure
void ValidateNode(FileSystemTreeNodeResponse node, int depth)
{
// ensure the current node's name and path match the expected segment
string expectedSegment = pathSegments[depth];
if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':'
&& !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedSegment += System.IO.Path.DirectorySeparatorChar;
node.Name.Should().Be(expectedSegment);
string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1));
if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedPath += System.IO.Path.DirectorySeparatorChar;
if (expectedPath.StartsWith("//"))
expectedPath = expectedPath[1..];
node.Path.Should().EndWith(expectedPath);
// if the node is a drive or directory, check its children recursively
if (node.ItemType is FileSystemItemType.Root or FileSystemItemType.Directory)
{
node.Children.Should().NotBeNull();
foreach (FileSystemTreeNodeResponse childNode in node.Children)
{
if (childNode.ItemType != FileSystemItemType.File) // go deeper one level, if the iterated node's children is also a directory
ValidateNode(childNode, depth + 1);
else if (childNode.ItemType is FileSystemItemType.File)
{
childNode.Children.Should().BeEmpty(); // files should not have children
childNode.Name.Should().BeOneOf((s_isUnix ? "." : string.Empty) + "TestFile_1.txt", "TestFile_2.txt");
}
}
}
}
FileSystemTreeNodeResponse rootNode = treeNodes!.Where(node => testPath.StartsWith(node.Name)).First();
ValidateNode(rootNode, 0);
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeFilesAndNotIncludeHiddenElements_ShouldReturnDirectoryTreeWithoutFiles()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
bool includeFiles = false;
bool includeHiddenElements = false;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
treeNodes.Should().NotBeNull();
treeNodes!.Should().NotBeEmpty();
// there should not be a File node
treeNodes.Should().AllSatisfy(node => node.ItemType.Should().BeOneOf(FileSystemItemType.Directory, FileSystemItemType.Root));
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
if (s_isUnix) // on UNIX, the leading slash is considered "the drive", the root location - add it!
pathSegments = ["/", .. pathSegments];
// recursively validate the tree structure
void ValidateNode(FileSystemTreeNodeResponse node, int depth)
{
// ensure the current node's name and path match the expected segment
string expectedSegment = pathSegments[depth];
if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':'
&& !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedSegment += System.IO.Path.DirectorySeparatorChar;
node.Name.Should().Be(expectedSegment);
string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1));
if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedPath += System.IO.Path.DirectorySeparatorChar;
if (expectedPath.StartsWith("//"))
expectedPath = expectedPath[1..];
node.Path.Should().EndWith(expectedPath);
node.Children.Should().NotBeNull();
foreach (FileSystemTreeNodeResponse childNode in node.Children)
ValidateNode(childNode, depth + 1);
}
FileSystemTreeNodeResponse rootNode = treeNodes!.Where(node => testPath.StartsWith(node.Name)).First();
ValidateNode(rootNode, 0);
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndNotIncludeFilesAndIncludeHiddenElements_ShouldReturnDirectoryTreeWithoutFiles()
{
// Arrange
FileSystemStructureFixture fileSystemFixture = new();
string testPath = fileSystemFixture.CreateFileSystemStructure();
bool includeFiles = false;
bool includeHiddenElements = true;
try
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(testPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? treeNodes = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
treeNodes.Should().NotBeNull();
treeNodes!.Should().NotBeEmpty();
// there should not be a File node
treeNodes.Should().AllSatisfy(node => node.ItemType.Should().BeOneOf(FileSystemItemType.Directory, FileSystemItemType.Root));
string[] pathSegments = testPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
if (s_isUnix) // on UNIX, the leading slash is considered "the drive", the root location - add it!
pathSegments = ["/", .. pathSegments];
// recursively validate the tree structure
void ValidateNode(FileSystemTreeNodeResponse node, int depth)
{
// ensure the current node's name and path match the expected segment
string expectedSegment = pathSegments[depth];
if (depth == 0 && node.ItemType == FileSystemItemType.Root && expectedSegment.Length == 2 && char.IsLetter(expectedSegment[0]) && expectedSegment[1] == ':'
&& !expectedSegment.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedSegment += System.IO.Path.DirectorySeparatorChar;
node.Name.Should().Be(expectedSegment);
string expectedPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), pathSegments.Take(depth + 1));
if (!expectedPath.EndsWith(System.IO.Path.DirectorySeparatorChar))
expectedPath += System.IO.Path.DirectorySeparatorChar;
if (expectedPath.StartsWith("//"))
expectedPath = expectedPath[1..];
node.Path.Should().EndWith(expectedPath);
node.Children.Should().NotBeNull();
foreach (FileSystemTreeNodeResponse childNode in node.Children)
ValidateNode(childNode, depth + 1);
}
FileSystemTreeNodeResponse rootNode = treeNodes!.Where(node => testPath.StartsWith(node.Name)).First();
ValidateNode(rootNode, 0);
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnValidationProblemResult()
{
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
bool includeFiles = false;
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directory-tree?path={Uri.EscapeDataString(encodedPath)}&includeFiles={includeFiles}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("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.Domain.Common.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories;
/// <summary>
/// Contains integration tests for the <see cref="GetTreeDirectoriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesEndpointTests : IClassFixture<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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTreeDirectoriesEndpointTests(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_isUnix ? "." : string.Empty) + "NestedDirectory_2");
firstNode.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : string.Empty) + "NestedDirectory_2" + System.IO.Path.DirectorySeparatorChar));
firstNode.ItemType.Should().Be(FileSystemItemType.Directory);
treeNodes.Should().AllSatisfy(n => n.ItemType.Should().Be(FileSystemItemType.Directory));
treeNodes!.Count.Should().Be(1); // only directories
}
finally
{
fileSystemFixture.CleanupFileSystemStructure();
}
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidPath_ShouldReturnForbiddenResult()
{
// Arrange
string invalidPath = "invalid:path";
string encodedPath = Uri.EscapeDataString(invalidPath);
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden);
problemDetails["title"].GetString().Should().Be("General.Failure");
problemDetails["instance"].GetString().Should().Be("/api/v1/directories/get-tree-directories");
problemDetails["detail"].GetString().Should().Be("UnauthorizedAccess");
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string emptyPath = "";
string encodedPath = Uri.EscapeDataString(emptyPath);
bool includeHiddenElements = true;
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-tree-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json");
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity);
problemDetails["title"].GetString().Should().Be("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>();
}
}
@@ -0,0 +1,65 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Domain.Common.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
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.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Drives;
/// <summary>
/// Contains integration tests for the <see cref="GetDrivesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDrivesEndpointTests : 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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
/// <summary>
/// Initializes a new instance of the <see cref="GetDrivesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDrivesEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldReturnDrives()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/drives/get-drives");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
List<FileSystemTreeNodeResponse>? drives = JsonSerializer.Deserialize<List<FileSystemTreeNodeResponse>>(content, _jsonOptions);
drives.Should().NotBeNull();
drives.Should().NotBeEmpty();
FileSystemTreeNodeResponse firstDrive = drives!.First();
firstDrive.Name.Should().Be(s_isUnix ? "/" : "C:\\");
firstDrive.Path.Should().Be(s_isUnix ? "/" : "C:\\");
firstDrive.ItemType.Should().Be(FileSystemItemType.Root);
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.Domain.Common.Enums.FileSystem;
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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
/// <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_isUnix ? "." : string.Empty) + "TestFile_1.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : 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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
/// <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_isUnix ? "." : string.Empty) + "TestFile_1.txt");
firstDirectory.Path.Should().Be(System.IO.Path.Combine(testPath, (s_isUnix ? "." : 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.Domain.Common.Enums.FileSystem;
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_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
/// <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_isUnix && 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>();
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
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.Maintenance.ApplicationSetup;
/// <summary>
/// Contains integration tests for the <see cref="CheckInitializationEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckInitializationEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly string _testUsername;
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CheckInitializationEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_testUsername = $"testuser_{Guid.NewGuid()}";
}
[Fact]
public async Task ExecuteAsync_WhenNoUsersExist_ShouldReturnNotInitialized()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/initialization");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
InitializationResponse? result = JsonSerializer.Deserialize<InitializationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsInitialized.Should().BeFalse();
}
[Fact]
public async Task ExecuteAsync_WhenUsersExist_ShouldReturnInitialized()
{
// Arrange
await CreateTestUser();
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/initialization");
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
InitializationResponse? result = JsonSerializer.Deserialize<InitializationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsInitialized.Should().BeTrue();
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
{
// Arrange
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel();
await _client.GetAsync("/api/v1/initialization", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = new()
{
Username = _testUsername,
Password = new HashService().HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
public void Dispose()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -0,0 +1,187 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// Contains integration tests for the <see cref="SetupApplicationEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetupApplicationEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly string _testUsername;
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetupApplicationEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_testUsername = $"testuser_{Guid.NewGuid()}";
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidRequestAnd2FA_ShouldSetupApplicationSuccessfully()
{
// Arrange
RegistrationRequest request = new(
Username: _testUsername,
Password: "TestPass123!",
PasswordConfirm: "TestPass123!",
Use2fa: true
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Created);
string content = await response.Content.ReadAsStringAsync();
RegistrationResponse? result = JsonSerializer.Deserialize<RegistrationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(_testUsername);
result.Id.Should().NotBe(Guid.Empty);
result.TotpSecret.Should().NotBeNullOrEmpty();
result.TotpSecret.Should().StartWith("data:image/png;base64,");
response.Headers.Location.Should().NotBeNull();
response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}");
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidRequestWithout2FA_ShouldSetupApplicationSuccessfully()
{
// Arrange
RegistrationRequest request = new(
Username: _testUsername,
Password: "TestPass123!",
PasswordConfirm: "TestPass123!",
Use2fa: false
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Created);
string content = await response.Content.ReadAsStringAsync();
RegistrationResponse? result = JsonSerializer.Deserialize<RegistrationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(_testUsername);
result.Id.Should().NotBe(Guid.Empty);
result.TotpSecret.Should().BeNull();
response.Headers.Location.Should().NotBeNull();
response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}");
}
[Fact]
public async Task ExecuteAsync_WhenAdminAccountAlreadyExists_ShouldReturnConflict()
{
// Arrange
await CreateTestUser();
RegistrationRequest request = new(
Username: "another_admin",
Password: "TestPass123!",
PasswordConfirm: "TestPass123!",
Use2fa: false
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request);
// 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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["title"].GetString().Should().Be("General.Unauthorized");
problemDetails["detail"].GetString().Should().Be("AdminAccountAlreadyCreated");
problemDetails["instance"].GetString().Should().Be("/api/v1/initialization");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError()
{
// Arrange
RegistrationRequest? request = null;
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation")
.WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]);
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = new()
{
Username = _testUsername,
Password = new HashService().HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
public void Dispose()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -0,0 +1,255 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.IntegrationTests.Common.Fixtures;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
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.UsersManagement.Authentication;
/// <summary>
/// Contains integration tests for the <see cref="ChangePasswordEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly HashService _hashService;
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly string _testUsername;
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ChangePasswordEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_hashService = new HashService();
_testUsername = $"testuser_{Guid.NewGuid()}";
// Set authorization header with unique username
string token = JwtFixture.GenerateJwtToken(_testUsername, ["User"]);
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldChangePasswordSuccessfully()
{
// Arrange
UserEntity user = await CreateTestUser();
ChangePasswordRequest request = new(
Username: user.Username,
CurrentPassword: "OldPass123!",
NewPassword: "NewPass123!",
NewPasswordConfirm: "NewPass123!"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
ChangePasswordResponse? result = JsonSerializer.Deserialize<ChangePasswordResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsPasswordChanged.Should().BeTrue();
}
[Fact]
public async Task ExecuteAsync_WhenPasswordsDoNotMatch_ShouldReturnValidationError()
{
// Arrange
UserEntity user = await CreateTestUser();
ChangePasswordRequest request = new(
Username: user.Username,
CurrentPassword: "OldPass123!",
NewPassword: "NewPass123!",
NewPasswordConfirm: "DifferentPass123!"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain("PasswordsNotMatch");
}
[Fact]
public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnNotFound()
{
// Arrange
ChangePasswordRequest request = new(
Username: "nonexistentuser",
CurrentPassword: "OldPass123!",
NewPassword: "NewPass123!",
NewPasswordConfirm: "NewPass123!"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
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.Status404NotFound);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
problemDetails["title"].GetString().Should().Be("General.NotFound");
problemDetails["detail"].GetString().Should().Be("UsernameDoesNotExist");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenCurrentPasswordIsIncorrect_ShouldReturnForbidden()
{
// Arrange
UserEntity user = await CreateTestUser();
ChangePasswordRequest request = new(
Username: user.Username,
CurrentPassword: "WrongPass123!",
NewPassword: "NewPass123!",
NewPasswordConfirm: "NewPass123!"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
// 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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["title"].GetString().Should().Be("General.Failure");
problemDetails["detail"].GetString().Should().Be("InvalidCurrentPassword");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError()
{
// Arrange
ChangePasswordRequest? request = null;
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "CurrentPasswordCannotBeEmpty", "NewPasswordCannotBeEmpty", "NewPasswordConfirmCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
{
// Arrange
UserEntity user = await CreateTestUser();
ChangePasswordRequest request = new(
Username: user.Username,
CurrentPassword: "OldPass123!",
NewPassword: "NewPass123!",
NewPasswordConfirm: "NewPass123!"
);
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel();
await _client.PostAsJsonAsync("/api/v1/auth/change-password", request, cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = new()
{
Username = _testUsername,
Password = _hashService.HashString("OldPass123!"),
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
public void Dispose()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -0,0 +1,319 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Authentication;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using OtpNet;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication;
/// <summary>
/// Contains integration tests for the <see cref="LoginEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly HashService _hashService;
private readonly ICryptographyService _cryptographyService;
private readonly TotpTokenGenerator _totpTokenGenerator;
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly string _testUsername;
/// <summary>
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public LoginEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_hashService = new HashService();
_totpTokenGenerator = new TotpTokenGenerator();
_testUsername = $"testuser_{Guid.NewGuid()}";
using IServiceScope scope = apiFactory.Services.CreateScope();
_cryptographyService = scope.ServiceProvider.GetRequiredService<ICryptographyService>();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidCredentials_ShouldLoginSuccessfully()
{
// Arrange
UserEntity user = await CreateTestUser();
LoginRequest request = new(
Username: user.Username,
Password: "TestPass123!"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(user.Username);
result.UsesTotp.Should().BeFalse();
result.Token.Should().NotBeNullOrEmpty();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidCredentialsAndTotp_ShouldLoginSuccessfully()
{
// Arrange
UserEntity user = await CreateTestUserWithTotp();
byte[] totpSecret = Convert.FromBase64String(_cryptographyService.Decrypt(user.TotpSecret!));
Totp totp = new(totpSecret);
string validTotpCode = totp.ComputeTotp(DateTime.UtcNow);
LoginRequest request = new(
Username: user.Username,
Password: "TestPass123!",
TotpCode: validTotpCode
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(user.Username);
result.UsesTotp.Should().BeTrue();
result.Token.Should().NotBeNullOrEmpty();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithTempPassword_ShouldLoginSuccessfully()
{
// Arrange
UserEntity user = await CreateTestUserWithTempPassword();
LoginRequest request = new(
Username: user.Username,
Password: "TempPass123!"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(user.Username);
result.Token.Should().NotBeNullOrEmpty();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithExpiredTempPassword_ShouldReturnUnauthorized()
{
// Arrange
UserEntity user = await CreateTestUserWithExpiredTempPassword();
LoginRequest request = new(
Username: user.Username,
Password: "TempPass123!"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
// 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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["title"].GetString().Should().Be("General.Failure");
problemDetails["detail"].GetString().Should().Be("TempPasswordExpired");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidCredentials_ShouldReturnUnauthorized()
{
// Arrange
UserEntity user = await CreateTestUser();
LoginRequest request = new(
Username: user.Username,
Password: "WrongPass123!"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
// 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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4");
problemDetails["title"].GetString().Should().Be("General.Failure");
problemDetails["detail"].GetString().Should().Be("InvalidUsernameOrPassword");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithInvalidTotpCode_ShouldReturnUnauthorized()
{
// Arrange
UserEntity user = await CreateTestUserWithTotp();
LoginRequest request = new(
Username: user.Username,
Password: "TestPass123!",
TotpCode: "000000"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]);
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = new()
{
Username = _testUsername,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
private async Task<UserEntity> CreateTestUserWithTotp()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
byte[] totpSecret = _totpTokenGenerator.GenerateSecret();
UserEntity user = new()
{
Username = _testUsername,
Password = _hashService.HashString("TestPass123!"),
TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)),
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
private async Task<UserEntity> CreateTestUserWithTempPassword()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = new()
{
Username = _testUsername,
Password = _hashService.HashString("TestPass123!"),
TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")),
TempPasswordCreated = DateTime.UtcNow,
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
private async Task<UserEntity> CreateTestUserWithExpiredTempPassword()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = new()
{
Username = _testUsername,
Password = _hashService.HashString("TestPass123!"),
TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")),
TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16), // expired (> 15 minutes old)
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
public void Dispose()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -0,0 +1,339 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Authentication;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OtpNet;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
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.UsersManagement.Authentication;
/// <summary>
/// Contains integration tests for the <see cref="RecoverPasswordEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RecoverPasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly HashService _hashService;
private readonly ICryptographyService _cryptographyService;
private readonly TotpTokenGenerator _totpTokenGenerator;
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly string _testUsername;
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RecoverPasswordEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_hashService = new HashService();
_totpTokenGenerator = new TotpTokenGenerator();
_testUsername = $"testuser_{Guid.NewGuid()}";
// get the encryption service with the test key from factory
using IServiceScope scope = apiFactory.Services.CreateScope();
_cryptographyService = scope.ServiceProvider.GetRequiredService<ICryptographyService>();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldResetPassword()
{
// Arrange
UserEntity user = await CreateUserWithTotp();
// decrypt the TOTP secret and generate a valid code
byte[] totpSecret = Convert.FromBase64String(_cryptographyService.Decrypt(user.TotpSecret!));
Totp totp = new(totpSecret);
string validTotpCode = totp.ComputeTotp(DateTime.UtcNow);
RecoverPasswordRequest request = new(
Username: user.Username,
TotpCode: validTotpCode
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
string content = await response.Content.ReadAsStringAsync();
RecoverPasswordResponse? result = JsonSerializer.Deserialize<RecoverPasswordResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsPasswordReset.Should().BeTrue();
// Create a new context to get fresh data
using IServiceScope verificationScope = _apiFactory.Services.CreateScope();
LuminaDbContext verificationContext = verificationScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// Ensure we get fresh data from the database
verificationContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
UserEntity? updatedUser = await verificationContext.Users
.AsNoTracking()
.FirstOrDefaultAsync(u => u.Username == user.Username);
updatedUser.Should().NotBeNull();
updatedUser!.TempPassword.Should().NotBeNull();
updatedUser.TempPasswordCreated.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(5));
}
[Fact]
public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnNotFound()
{
// Arrange
RecoverPasswordRequest request = new(
Username: "nonexistentuser",
TotpCode: "123456"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
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.Status404NotFound);
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5");
problemDetails["title"].GetString().Should().Be("General.NotFound");
problemDetails["detail"].GetString().Should().Be("UsernameDoesNotExist");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task ExecuteAsync_WhenInvalidTotpCode_ShouldReturnForbidden()
{
// Arrange
UserEntity user = await CreateUserWithTotp();
RecoverPasswordRequest request = new(
Username: user.Username,
TotpCode: "000000"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]);
}
[Fact]
public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError()
{
// Arrange
RecoverPasswordRequest? request = null;
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "TotpCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenUserDoesNotUseTotpAndTriesToRecover_ShouldReturnForbidden()
{
// Arrange
UserEntity user = await CreateUserWithoutTotp();
RecoverPasswordRequest request = new(
Username: user.Username,
TotpCode: "123456"
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]);
}
[Fact]
public async Task ExecuteAsync_WhenUserDoesNotUseTotpAndTriesToRecoverWithoutCode_ShouldReturnForbidden()
{
// Arrange
// Setup user without TOTP
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity userWithoutTotp = new()
{
Username = "userwithoutotp2",
Password = _hashService.HashString("OldPass123!"),
TotpSecret = null, // No TOTP configured
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(userWithoutTotp);
await dbContext.SaveChangesAsync();
}
RecoverPasswordRequest request = new(
Username: "userwithoutotp2",
TotpCode: null
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
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["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2");
problemDetails["title"].GetString().Should().Be("Validation Error");
problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred.");
problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password");
problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace();
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["TotpCannotBeEmpty"]);
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
{
// Arrange
RecoverPasswordRequest request = new(
Username: "testuser",
TotpCode: "123456"
);
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel();
await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request, cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
private async Task<UserEntity> CreateUserWithTotp()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
byte[] totpSecret = _totpTokenGenerator.GenerateSecret();
UserEntity user = new()
{
Username = _testUsername,
Password = _hashService.HashString("OldPass123!"),
TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)),
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
private async Task<UserEntity> CreateUserWithoutTotp()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = new()
{
Username = _testUsername,
Password = _hashService.HashString("OldPass123!"),
TotpSecret = null,
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
public void Dispose()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -0,0 +1,205 @@
#region ========================================================================= USING =====================================================================================
using FluentAssertions;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication;
/// <summary>
/// Contains integration tests for the <see cref="RegisterEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly string _testUsername;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RegisterEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_testUsername = $"testuser_{Guid.NewGuid()}";
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldRegisterUserSuccessfully()
{
// Arrange
RegistrationRequest request = new(
Username: _testUsername,
Password: "TestPass123!",
PasswordConfirm: "TestPass123!",
Use2fa: false
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Created);
string content = await response.Content.ReadAsStringAsync();
RegistrationResponse? result = JsonSerializer.Deserialize<RegistrationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(_testUsername);
result.Id.Should().NotBe(Guid.Empty);
result.TotpSecret.Should().BeNull();
response.Headers.Location.Should().NotBeNull();
response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}");
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidRequestAnd2FA_ShouldRegisterUserWithTotp()
{
// Arrange
RegistrationRequest request = new(
Username: _testUsername,
Password: "TestPass123!",
PasswordConfirm: "TestPass123!",
Use2fa: true
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Created);
string content = await response.Content.ReadAsStringAsync();
RegistrationResponse? result = JsonSerializer.Deserialize<RegistrationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Username.Should().Be(_testUsername);
result.Id.Should().NotBe(Guid.Empty);
result.TotpSecret.Should().NotBeNullOrEmpty();
result.TotpSecret.Should().StartWith("data:image/png;base64,");
}
[Fact]
public async Task ExecuteAsync_WhenUsernameAlreadyExists_ShouldReturnConflict()
{
// Arrange
await CreateTestUser();
RegistrationRequest request = new(
Username: _testUsername,
Password: "TestPass123!",
PasswordConfirm: "TestPass123!",
Use2fa: false
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Conflict);
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.Status409Conflict);
problemDetails["title"].GetString().Should().Be("General.Conflict");
problemDetails["detail"].GetString().Should().Be("UsernameAlreadyExists");
}
[Fact]
public async Task ExecuteAsync_WhenPasswordsDoNotMatch_ShouldReturnValidationError()
{
// Arrange
RegistrationRequest request = new(
Username: _testUsername,
Password: "TestPass123!",
PasswordConfirm: "DifferentPass123!",
Use2fa: false
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain("PasswordsNotMatch");
}
[Fact]
public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError()
{
// Arrange
RegistrationRequest? request = null;
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation")
.WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]);
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = new()
{
Username = _testUsername,
Password = new HashService().HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
return user;
}
public void Dispose()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -1,20 +1,19 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Bogus;
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.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System;
using System.Collections.Generic;
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 +45,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(
ReleaseInfoDto releaseInfo = new Faker<ReleaseInfoDto>()
.CustomInstantiator(f => new ReleaseInfoDto(
default,
default,
default,
@@ -63,44 +62,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<GenreDto> genre = new Faker<GenreDto>()
.CustomInstantiator(f => new GenreDto(
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<TagDto> tag = new Faker<TagDto>()
.CustomInstantiator(f => new TagDto(
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<MediaContributorRoleDto> mediaContributorRole = new Faker<MediaContributorRoleDto>()
.CustomInstantiator(f => new MediaContributorRoleDto(
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<MediaContributorNameDto> mediaContributorName = new Faker<MediaContributorNameDto>()
.CustomInstantiator(f => new MediaContributorNameDto(
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<MediaContributorDto> mediaContributor = new Faker<MediaContributorDto>()
.CustomInstantiator(f => new MediaContributorDto(
default!,
default!
))
.RuleFor(e => e.Name, mediaContributorName)
.RuleFor(e => e.Role, mediaContributorRole);
Faker<BookRatingModel> rating = new Faker<BookRatingModel>()
.CustomInstantiator(f => new BookRatingModel(
Faker<BookRatingDto> rating = new Faker<BookRatingDto>()
.CustomInstantiator(f => new BookRatingDto(
default,
default,
default,
@@ -111,8 +110,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<LanguageInfoDto> language = new Faker<LanguageInfoDto>()
.CustomInstantiator(f => new LanguageInfoDto(
default!,
default!,
default
@@ -121,8 +120,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<LanguageInfoDto> originalLanguage = new Faker<LanguageInfoDto>()
.CustomInstantiator(f => new LanguageInfoDto(
default!,
default!,
default
@@ -131,8 +130,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<WrittenContentMetadataDto> metadata = new Faker<WrittenContentMetadataDto>()
.CustomInstantiator(f => new WrittenContentMetadataDto(
default!,
default,
default,
@@ -155,8 +154,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<IsbnDto> isbn = new Faker<IsbnDto>()
.CustomInstantiator(f => new IsbnDto(
default!,
default
))
@@ -272,72 +271,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;
}
}
@@ -1,19 +1,19 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using System;
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.BoundedContexts.WrittenContentLibraryBoundedContext.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>();
}
}
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
@@ -9,21 +9,28 @@
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="5.0.0-preview0011" />
<PackageReference Include="AutoFixture.Xunit2" Version="5.0.0-preview0011" />
<PackageReference Include="Bogus" Version="35.6.0" />
<PackageReference Include="Bogus" Version="35.6.1" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.0-rc.2.24474.3" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0-rc.2.24473.5" />
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.35">
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.49">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>