mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 16:11:10 +00:00
Updates to .NET 9.0
This commit is contained in:
commit
acbdb0a5f8
853 files changed
+34993
-10123
No files matched your search
+12
-5
@@ -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>
|
||||
|
||||
+16
-16
@@ -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(
|
||||
|
||||
+49
@@ -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);
|
||||
}
|
||||
}
|
||||
+38
-4
@@ -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.
|
||||
|
||||
-639
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
-79
@@ -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);
|
||||
}
|
||||
}
|
||||
-329
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
-634
@@ -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>();
|
||||
}
|
||||
}
|
||||
-130
@@ -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>();
|
||||
}
|
||||
}
|
||||
+204
@@ -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>();
|
||||
}
|
||||
}
|
||||
+411
@@ -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>();
|
||||
}
|
||||
}
|
||||
+247
@@ -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>();
|
||||
}
|
||||
}
|
||||
+65
@@ -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);
|
||||
}
|
||||
}
|
||||
+14
-18
@@ -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();
|
||||
+243
@@ -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>();
|
||||
}
|
||||
}
|
||||
+243
@@ -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>();
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -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))
|
||||
+3
-3
@@ -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.Application.UnitTests.Core.FileManagement.Directories.Fixtures;
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemManagement.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FileSystemTreeNodeResponse"/> class.
|
||||
+2
-2
@@ -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();
|
||||
}
|
||||
|
||||
+126
@@ -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>();
|
||||
}
|
||||
}
|
||||
+123
@@ -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>();
|
||||
}
|
||||
}
|
||||
+191
@@ -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>();
|
||||
}
|
||||
}
|
||||
+149
@@ -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>();
|
||||
}
|
||||
|
||||
}
|
||||
+105
@@ -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>();
|
||||
}
|
||||
}
|
||||
+132
@@ -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>();
|
||||
}
|
||||
}
|
||||
+110
@@ -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>();
|
||||
}
|
||||
}
|
||||
+155
@@ -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>();
|
||||
}
|
||||
}
|
||||
+132
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+187
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+255
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+319
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+339
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+205
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+237
-252
File diff suppressed because it is too large.
Load diff
+29
-98
@@ -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;
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -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.
|
||||
+86
@@ -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>();
|
||||
}
|
||||
}
|
||||
+14
-7
@@ -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>
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
#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.Diagnostics.CodeAnalysis;
|
||||
using System.Text;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating a web application for security tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
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.
|
||||
/// </summary>
|
||||
public LuminaApiFactory()
|
||||
{
|
||||
_connection = new SqliteConnection("DataSource=:memory:");
|
||||
_connection.Open();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the web host for the security tests.
|
||||
/// </summary>
|
||||
/// <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",
|
||||
["JwtSettings:ExpiryMinutes"] = "15", // control the expiry time during tests
|
||||
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key
|
||||
});
|
||||
});
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
// remove existing DbContext configuration
|
||||
ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
|
||||
if (descriptor is not null)
|
||||
services.Remove(descriptor);
|
||||
// add SQLite DbContext configuration
|
||||
services.AddDbContext<LuminaDbContext>(options => options.UseSqlite(_connection));
|
||||
// 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.Migrate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the connection to the database.
|
||||
/// </summary>
|
||||
public new void Dispose()
|
||||
{
|
||||
_connection.Close();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
#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.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/auth/change-password</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthChangePasswordTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly HashService _hashService;
|
||||
private readonly string _testUsername;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AuthLoginTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AuthChangePasswordTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.12");
|
||||
_hashService = new HashService();
|
||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WithoutAuthentication_ShouldReturn401()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = new(
|
||||
Username: _testUsername,
|
||||
CurrentPassword: "OldPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WithValidRequest_ShouldNotLeakTimingInformation()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateAndAuthenticateUser();
|
||||
Stopwatch stopwatch = new();
|
||||
List<long> timings = [];
|
||||
|
||||
// Act
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
stopwatch.Restart();
|
||||
await _client.PostAsJsonAsync("/api/v1/auth/change-password", new ChangePasswordRequest(
|
||||
Username: user.Username,
|
||||
CurrentPassword: "WrongPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
));
|
||||
stopwatch.Stop();
|
||||
timings.Add(stopwatch.ElapsedMilliseconds);
|
||||
}
|
||||
|
||||
timings.Sort();
|
||||
timings = timings.Skip(1).SkipLast(1).ToList(); // remove outliers
|
||||
|
||||
// Assert
|
||||
double stdDev = CalculateStandardDeviation(timings);
|
||||
stdDev.Should().BeLessThan(200);
|
||||
}
|
||||
|
||||
private double CalculateStandardDeviation(List<long> values)
|
||||
{
|
||||
double average = values.Average();
|
||||
double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum();
|
||||
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
|
||||
}
|
||||
|
||||
private async Task<UserEntity> CreateAndAuthenticateUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// create test user
|
||||
UserEntity user = new()
|
||||
{
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
Created = DateTime.UtcNow
|
||||
};
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// authenticate user
|
||||
LoginRequest loginRequest = new(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!"
|
||||
);
|
||||
|
||||
HttpResponseMessage loginResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// set auth header for subsequent requests
|
||||
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
_client.DefaultRequestHeaders.Authorization = null;
|
||||
}
|
||||
}
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
#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.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/auth/login</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthLoginTests : 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="AuthLoginTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AuthLoginTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// set a fake IP for this test instance
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.1");
|
||||
_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 Login_WithValidCredentials_ShouldAuthenticateSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!"
|
||||
);
|
||||
DateTimeOffset beforeRequest = DateTimeOffset.UtcNow;
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.10");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
JwtSecurityTokenHandler handler = new();
|
||||
JwtSecurityToken token = handler.ReadJwtToken(result!.Token);
|
||||
|
||||
string expValue = token.Claims.First(c => c.Type == "exp").Value; // get token claims
|
||||
DateTimeOffset tokenExpiration = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expValue));
|
||||
DateTimeOffset expectedExpiration = beforeRequest.AddMinutes(15);
|
||||
|
||||
// verify token duration (should be 15 minutes from request time - expiration value is set in tests setup class)
|
||||
TimeSpan allowedVariance = TimeSpan.FromSeconds(30); // allow for processing time
|
||||
TimeSpan actualDifference = tokenExpiration - beforeRequest;
|
||||
TimeSpan expectedDifference = TimeSpan.FromMinutes(15);
|
||||
|
||||
actualDifference.Should().BeCloseTo(expectedDifference, precision: allowedVariance);
|
||||
|
||||
token.Header.Alg.Should().Be("HS256");
|
||||
token.Claims.Should().Contain(c => c.Type == "sub" && c.Value == user.Id.ToString());
|
||||
token.Claims.Should().Contain(c => c.Type == "unique_name" && c.Value == user.Username);
|
||||
token.Claims.Should().Contain(c => c.Type == "jti");
|
||||
token.Claims.Should().Contain(c => c.Type == "iss" && c.Value == "Lumina");
|
||||
token.Claims.Should().Contain(c => c.Type == "aud" && c.Value == "Lumina");
|
||||
|
||||
content.Should().NotContain("password");
|
||||
content.Should().NotContain("hash");
|
||||
content.Should().NotContain("salt");
|
||||
|
||||
// TODO: implement more strict security checks:
|
||||
// // check security headers
|
||||
// response.Headers.Should().ContainKey("X-Content-Type-Options")
|
||||
// .WhoseValue.Should().Contain("nosniff");
|
||||
// response.Headers.Should().ContainKey("X-Frame-Options")
|
||||
// .WhoseValue.Should().Contain("DENY");
|
||||
// response.Headers.Should().ContainKey("X-XSS-Protection")
|
||||
// .WhoseValue.Should().Contain("1; mode=block");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithValidCredentials_ShouldNotLeakTimingInformation()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
Stopwatch stopwatch = new();
|
||||
List<long> timings = [];
|
||||
// since this test is rigged to trigger the rate limiting, assign a different IP to it
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.2");
|
||||
|
||||
// Act
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
await Task.Delay(100); // add small delay between requests
|
||||
stopwatch.Restart();
|
||||
await _client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!"
|
||||
));
|
||||
stopwatch.Stop();
|
||||
timings.Add(stopwatch.ElapsedMilliseconds);
|
||||
}
|
||||
// remove the highest and lowest values to account for outliers
|
||||
timings.Sort();
|
||||
timings = timings.Skip(1).SkipLast(1).ToList();
|
||||
|
||||
// Assert
|
||||
// check for timing consistency to prevent timing attacks
|
||||
double stdDev = CalculateStandardDeviation(timings);
|
||||
stdDev.Should().BeLessThan(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests()
|
||||
{
|
||||
// Arrange
|
||||
// set a fake IP for this test instance
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.3");
|
||||
LoginRequest request = new(
|
||||
Username: "testuser",
|
||||
Password: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
List<HttpResponseMessage> responses = [];
|
||||
for (int i = 0; i < 11; i++) // exceed the 10 request limit
|
||||
responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/login", request));
|
||||
|
||||
// Assert
|
||||
HttpResponseMessage lastResponse = responses.Last();
|
||||
lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
|
||||
string content = await lastResponse.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29");
|
||||
problemDetails["title"].GetString().Should().Be("TooManyRequests");
|
||||
problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later.");
|
||||
problemDetails["retryAfter"].GetString().Should().Be("15");
|
||||
|
||||
lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit");
|
||||
lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset");
|
||||
lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("admin'--")] // comment injection
|
||||
[InlineData("' UNION SELECT * FROM Users--")] // union injection
|
||||
[InlineData("'; DROP TABLE Users--")] // destructive injection
|
||||
[InlineData("' WAITFOR DELAY '0:0:10'--")] // time-based injection
|
||||
public async Task Login_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername)
|
||||
{
|
||||
// Arrange
|
||||
UserEntity legitimateUser = await CreateTestUser();
|
||||
LoginRequest request = new(
|
||||
Username: maliciousUsername,
|
||||
Password: "Abcd123$"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
content.Should().NotContain("SQL");
|
||||
content.Should().NotContain("Exception");
|
||||
content.Should().NotContain(legitimateUser.Username); // shouldn't expose other usernames
|
||||
content.Should().NotContain(legitimateUser.Password); // shouldn't expose password hashes
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithSQLInjectionInValidUser_ShouldRemainSecure()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "' OR '1'='1"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.11");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
content.Should().NotContain("SQL");
|
||||
content.Should().NotContain("Exception");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithInjectionInTotpCode_ShouldRemainSecure()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUserWithTotp();
|
||||
LoginRequest request = new(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!",
|
||||
TotpCode: "' OR '1'='1"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
|
||||
content.Should().NotContain("SQL");
|
||||
content.Should().NotContain("Exception");
|
||||
}
|
||||
|
||||
private double CalculateStandardDeviation(List<long> values)
|
||||
{
|
||||
double average = values.Average();
|
||||
double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum();
|
||||
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/auth/recover-password</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthRecoverPasswordTests : 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="AuthRecoverPasswordTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AuthRecoverPasswordTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// set a fake IP for this test instance
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.4");
|
||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordRequest request = new(
|
||||
Username: "testuser",
|
||||
TotpCode: "123456"
|
||||
);
|
||||
|
||||
// Act
|
||||
List<HttpResponseMessage> responses = [];
|
||||
for (int i = 0; i < 11; i++) // exceed the 10 request limit
|
||||
responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request));
|
||||
|
||||
// Assert
|
||||
HttpResponseMessage lastResponse = responses.Last();
|
||||
lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
|
||||
string content = await lastResponse.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29");
|
||||
problemDetails["title"].GetString().Should().Be("TooManyRequests");
|
||||
problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later.");
|
||||
problemDetails["retryAfter"].GetString().Should().Be("15");
|
||||
|
||||
lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit");
|
||||
lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset");
|
||||
lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining");
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/auth/register</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AuthRegisterTests : 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;
|
||||
|
||||
public AuthRegisterTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.5");
|
||||
_hashService = new HashService();
|
||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WithValidData_ShouldNotLeakTimingInformation()
|
||||
{
|
||||
// Arrange
|
||||
Stopwatch stopwatch = new();
|
||||
List<long> timings = [];
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6");
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
stopwatch.Restart();
|
||||
await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
stopwatch.Stop();
|
||||
timings.Add(stopwatch.ElapsedMilliseconds);
|
||||
}
|
||||
timings.Sort();
|
||||
timings = timings.Skip(1).SkipLast(1).ToList();
|
||||
|
||||
// Assert
|
||||
double stdDev = CalculateStandardDeviation(timings);
|
||||
stdDev.Should().BeLessThan(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WhenRateLimitExceeded_ShouldReturnTooManyRequests()
|
||||
{
|
||||
// Arrange
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.7");
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
List<HttpResponseMessage> responses = [];
|
||||
for (int i = 0; i < 11; i++)
|
||||
responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/register", request));
|
||||
|
||||
// Assert
|
||||
HttpResponseMessage lastResponse = responses.Last();
|
||||
lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
|
||||
string content = await lastResponse.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
problemDetails.Should().NotBeNull();
|
||||
problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests);
|
||||
problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29");
|
||||
problemDetails["title"].GetString().Should().Be("TooManyRequests");
|
||||
problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later.");
|
||||
problemDetails["retryAfter"].GetString().Should().Be("15");
|
||||
|
||||
lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit");
|
||||
lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset");
|
||||
lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("admin'--")] // comment injection
|
||||
[InlineData("' UNION SELECT * FROM Users--")] // union injection
|
||||
[InlineData("'; DROP TABLE Users--")] // destructive injection
|
||||
[InlineData("' WAITFOR DELAY '0:0:10'--")] // time-based injection
|
||||
public async Task Register_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername)
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: maliciousUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
|
||||
content.Should().NotContain("SQL");
|
||||
content.Should().NotContain("Exception");
|
||||
content.Should().NotContain("password");
|
||||
content.Should().NotContain("hash");
|
||||
content.Should().NotContain("salt");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("password123")] // common password
|
||||
[InlineData("123456789")] // numeric only
|
||||
[InlineData("abcdefgh")] // lowercase only
|
||||
[InlineData("short")] // too short
|
||||
public async Task Register_WithWeakPassword_ShouldBeDenied(string weakPassword)
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: weakPassword,
|
||||
PasswordConfirm: weakPassword
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.8");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
|
||||
content.Should().NotContain(weakPassword); // shouldn't leak the actual password
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("TestPass123!")] // valid password
|
||||
[InlineData("Ab1!defghijklmnopqrstuvwxyz")] // long password
|
||||
public async Task Register_WithValidPassword_ShouldAcceptPassword(string password)
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: password,
|
||||
PasswordConfirm: password
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WithExistingUsername_ShouldNotLeakUserExistence()
|
||||
{
|
||||
// Arrange
|
||||
await CreateTestUser();
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.9");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Conflict);
|
||||
content.Should().NotContain(_testUsername);
|
||||
content.Should().NotContain("password");
|
||||
content.Should().NotContain("hash");
|
||||
content.Should().NotContain("salt");
|
||||
}
|
||||
|
||||
private double CalculateStandardDeviation(List<long> values)
|
||||
{
|
||||
double average = values.Average();
|
||||
double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum();
|
||||
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<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.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.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.3.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.49">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Api\Lumina.Presentation.Api.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Converters.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="OptionalJsonConverterFactory"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OptionalJsonConverterFactoryFixture
|
||||
{
|
||||
}
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Converters;
|
||||
using Lumina.Application.UnitTests.Common.Converters.Fixtures;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFilesQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OptionalJsonConverterFactoryTests
|
||||
{
|
||||
private readonly OptionalJsonConverterFactory _factory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OptionalJsonConverterFactoryTests"/> class.
|
||||
/// </summary>
|
||||
public OptionalJsonConverterFactoryTests()
|
||||
{
|
||||
_factory = new OptionalJsonConverterFactory();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanConvert_WhenTypeIsOptional_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Type typeToConvert = typeof(Optional<string>);
|
||||
|
||||
// Act
|
||||
bool result = _factory.CanConvert(typeToConvert);
|
||||
|
||||
// Assert
|
||||
result.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanConvert_WhenTypeIsNotOptional_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Type typeToConvert = typeof(string);
|
||||
|
||||
// Act
|
||||
bool result = _factory.CanConvert(typeToConvert);
|
||||
|
||||
// Assert
|
||||
result.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanConvert_WhenTypeIsGenericButNotOptional_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Type typeToConvert = typeof(List<string>);
|
||||
|
||||
// Act
|
||||
bool result = _factory.CanConvert(typeToConvert);
|
||||
|
||||
// Assert
|
||||
result.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateConverter_WhenTypeIsOptionalString_ShouldReturnCorrectConverterType()
|
||||
{
|
||||
// Arrange
|
||||
Type typeToConvert = typeof(Optional<string>);
|
||||
JsonSerializerOptions options = new();
|
||||
|
||||
// Act
|
||||
JsonConverter converter = _factory.CreateConverter(typeToConvert, options);
|
||||
|
||||
// Assert
|
||||
converter.Should().BeOfType<OptionalJsonConverter<string>>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateConverter_WhenTypeIsOptionalInt_ShouldReturnCorrectConverterType()
|
||||
{
|
||||
// Arrange
|
||||
Type typeToConvert = typeof(Optional<int>);
|
||||
JsonSerializerOptions options = new();
|
||||
|
||||
// Act
|
||||
JsonConverter converter = _factory.CreateConverter(typeToConvert, options);
|
||||
|
||||
// Assert
|
||||
converter.Should().BeOfType<OptionalJsonConverter<int>>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateConverter_WhenTypeIsOptionalCustomClass_ShouldReturnCorrectConverterType()
|
||||
{
|
||||
// Arrange
|
||||
Type typeToConvert = typeof(Optional<OptionalJsonConverterFactoryFixture>);
|
||||
JsonSerializerOptions options = new();
|
||||
|
||||
// Act
|
||||
JsonConverter converter = _factory.CreateConverter(typeToConvert, options);
|
||||
|
||||
// Assert
|
||||
converter.Should().BeOfType<OptionalJsonConverter<OptionalJsonConverterFactoryFixture>>();
|
||||
}
|
||||
}
|
||||
-136
@@ -1,136 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Converters;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="OptionalJsonConverter"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OptionalJsonConverterTests
|
||||
{
|
||||
private readonly JsonSerializerOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OptionalJsonConverterTests"/> class.
|
||||
/// </summary>
|
||||
public OptionalJsonConverterTests()
|
||||
{
|
||||
_options = new JsonSerializerOptions();
|
||||
_options.Converters.Add(new OptionalJsonConverter<string>());
|
||||
_options.Converters.Add(new OptionalJsonConverter<int>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenJsonIsNull_ShouldReturnNone()
|
||||
{
|
||||
// Arrange
|
||||
string json = "null";
|
||||
|
||||
// Act
|
||||
Optional<string> result = JsonSerializer.Deserialize<Optional<string>>(json, _options);
|
||||
|
||||
// Assert
|
||||
result.HasValue.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenJsonHasStringValue_ShouldReturnSomeWithCorrectValue()
|
||||
{
|
||||
// Arrange
|
||||
string json = "\"test\"";
|
||||
|
||||
// Act
|
||||
Optional<string> result = JsonSerializer.Deserialize<Optional<string>>(json, _options);
|
||||
|
||||
// Assert
|
||||
result.HasValue.Should().BeTrue();
|
||||
result.Value.Should().Be("test");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenJsonHasIntValue_ShouldReturnSomeWithCorrectValue()
|
||||
{
|
||||
// Arrange
|
||||
string json = "42";
|
||||
|
||||
// Act
|
||||
Optional<int> result = JsonSerializer.Deserialize<Optional<int>>(json, _options);
|
||||
|
||||
// Assert
|
||||
result.HasValue.Should().BeTrue();
|
||||
result.Value.Should().Be(42);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_WhenOptionalHasNoValue_ShouldWriteNull()
|
||||
{
|
||||
// Arrange
|
||||
Optional<string> optional = Optional<string>.None();
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(optional, _options);
|
||||
|
||||
// Assert
|
||||
json.Should().Be("null");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_WhenOptionalHasStringValue_ShouldWriteCorrectJson()
|
||||
{
|
||||
// Arrange
|
||||
Optional<string> optional = Optional<string>.Some("test");
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(optional, _options);
|
||||
|
||||
// Assert
|
||||
json.Should().Be("\"test\"");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_WhenOptionalHasIntValue_ShouldWriteCorrectJson()
|
||||
{
|
||||
// Arrange
|
||||
Optional<int> optional = Optional<int>.Some(42);
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(optional, _options);
|
||||
|
||||
// Assert
|
||||
json.Should().Be("42");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadWrite_WhenSerializingAndDeserializingSomeValue_ShouldPreserveValue()
|
||||
{
|
||||
// Arrange
|
||||
Optional<string> original = Optional<string>.Some("test");
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(original, _options);
|
||||
Optional<string> deserialized = JsonSerializer.Deserialize<Optional<string>>(json, _options);
|
||||
|
||||
// Assert
|
||||
deserialized.Should().Be(original);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadWrite_WhenSerializingAndDeserializingNone_ShouldPreserveNone()
|
||||
{
|
||||
// Arrange
|
||||
Optional<string> original = Optional<string>.None();
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(original, _options);
|
||||
Optional<string> deserialized = JsonSerializer.Deserialize<Optional<string>>(json, _options);
|
||||
|
||||
// Assert
|
||||
deserialized.Should().Be(original);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
|
||||
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.ChangePassword.Fixtures;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Lumina.Application.Common.Mapping.Authentication;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ChangePasswordRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordRequestMappingTests
|
||||
{
|
||||
private readonly ChangePasswordRequestFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public ChangePasswordRequestMappingTests()
|
||||
{
|
||||
_fixture = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = _fixture.CreateChangePasswordRequest();
|
||||
|
||||
// Act
|
||||
ChangePasswordCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(request.Username);
|
||||
result.CurrentPassword.Should().Be(request.CurrentPassword);
|
||||
result.NewPassword.Should().Be(request.NewPassword);
|
||||
result.NewPasswordConfirm.Should().Be(request.NewPasswordConfirm);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = new(null, null, null, null);
|
||||
|
||||
// Act
|
||||
ChangePasswordCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().BeNull();
|
||||
result.CurrentPassword.Should().BeNull();
|
||||
result.NewPassword.Should().BeNull();
|
||||
result.NewPasswordConfirm.Should().BeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("user1", "oldPass", "newPass", "newPass")]
|
||||
[InlineData("", "", "", "")]
|
||||
[InlineData("testUser", null, "pass123", "pass123")]
|
||||
public void ToCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly(
|
||||
string? username,
|
||||
string? currentPassword,
|
||||
string? newPassword,
|
||||
string? newPasswordConfirm)
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = new(username, currentPassword, newPassword, newPasswordConfirm);
|
||||
|
||||
// Act
|
||||
ChangePasswordCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(username);
|
||||
result.CurrentPassword.Should().Be(currentPassword);
|
||||
result.NewPassword.Should().Be(newPassword);
|
||||
result.NewPasswordConfirm.Should().Be(newPasswordConfirm);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.Authentication;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
|
||||
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Queries.LoginUser.Fixtures;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LoginRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginRequestMappingTests
|
||||
{
|
||||
private readonly LoginRequestFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public LoginRequestMappingTests()
|
||||
{
|
||||
_fixture = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
LoginRequest request = _fixture.CreateLoginRequest();
|
||||
|
||||
// Act
|
||||
LoginUserQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(request.Username);
|
||||
result.Password.Should().Be(request.Password);
|
||||
result.TotpCode.Should().Be(request.TotpCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingRequestWithNullValues_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
LoginRequest request = new(null, null);
|
||||
|
||||
// Act
|
||||
LoginUserQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().BeNull();
|
||||
result.Password.Should().BeNull();
|
||||
result.TotpCode.Should().BeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("user1", "pass123", "123456")]
|
||||
[InlineData("", "", "")]
|
||||
[InlineData("testUser", null, null)]
|
||||
[InlineData("admin", "admin123", null)]
|
||||
public void ToQuery_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly(
|
||||
string? username,
|
||||
string? password,
|
||||
string? totpCode)
|
||||
{
|
||||
// Arrange
|
||||
LoginRequest request = new(username, password, totpCode);
|
||||
|
||||
// Act
|
||||
LoginUserQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(username);
|
||||
result.Password.Should().Be(password);
|
||||
result.TotpCode.Should().Be(totpCode);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.Authentication;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
|
||||
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RecoverPassword.Fixtures;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RecoverPasswordRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordRequestMappingTests
|
||||
{
|
||||
private readonly RecoverPasswordRequestFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public RecoverPasswordRequestMappingTests()
|
||||
{
|
||||
_fixture = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordRequest request = _fixture.CreateRecoverPasswordRequest();
|
||||
|
||||
// Act
|
||||
RecoverPasswordCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(request.Username);
|
||||
result.TotpCode.Should().Be(request.TotpCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordRequest request = new(null, null);
|
||||
|
||||
// Act
|
||||
RecoverPasswordCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().BeNull();
|
||||
result.TotpCode.Should().BeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("user1", "123456")]
|
||||
[InlineData("", "")]
|
||||
[InlineData("testUser", null)]
|
||||
[InlineData(null, "654321")]
|
||||
public void ToCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly(
|
||||
string? username,
|
||||
string? totpCode)
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordRequest request = new(username, totpCode);
|
||||
|
||||
// Act
|
||||
RecoverPasswordCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(username);
|
||||
result.TotpCode.Should().Be(totpCode);
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.Authentication;
|
||||
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication;
|
||||
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||
using Lumina.Application.UnitTests.Core.UsersManagement.Authentication.Commands.RegisterUser.Fixture;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RegistrationRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegistrationRequestMappingTests
|
||||
{
|
||||
private readonly RegistrationRequestFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegistrationRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public RegistrationRequestMappingTests()
|
||||
{
|
||||
_fixture = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToSetupCommand_WhenMappingRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = _fixture.CreateRegistrationRequest();
|
||||
|
||||
// Act
|
||||
SetupApplicationCommand result = request.ToSetupCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(request.Username);
|
||||
result.Password.Should().Be(request.Password);
|
||||
result.PasswordConfirm.Should().Be(request.PasswordConfirm);
|
||||
result.Use2fa.Should().Be(request.Use2fa);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = _fixture.CreateRegistrationRequest();
|
||||
|
||||
// Act
|
||||
RegisterUserCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(request.Username);
|
||||
result.Password.Should().Be(request.Password);
|
||||
result.PasswordConfirm.Should().Be(request.PasswordConfirm);
|
||||
result.Use2fa.Should().Be(request.Use2fa);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToSetupCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new();
|
||||
|
||||
// Act
|
||||
SetupApplicationCommand result = request.ToSetupCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().BeNull();
|
||||
result.Password.Should().BeNull();
|
||||
result.PasswordConfirm.Should().BeNull();
|
||||
result.Use2fa.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequestWithNullValues_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new();
|
||||
|
||||
// Act
|
||||
RegisterUserCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().BeNull();
|
||||
result.Password.Should().BeNull();
|
||||
result.PasswordConfirm.Should().BeNull();
|
||||
result.Use2fa.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("user1", "pass123", "pass123", true)]
|
||||
[InlineData("", "", "", false)]
|
||||
[InlineData("testUser", null, null, true)]
|
||||
[InlineData(null, "pass123", "pass123", false)]
|
||||
public void ToSetupCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly(
|
||||
string? username,
|
||||
string? password,
|
||||
string? passwordConfirm,
|
||||
bool use2fa)
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(username, password, passwordConfirm, use2fa);
|
||||
|
||||
// Act
|
||||
SetupApplicationCommand result = request.ToSetupCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(username);
|
||||
result.Password.Should().Be(password);
|
||||
result.PasswordConfirm.Should().Be(passwordConfirm);
|
||||
result.Use2fa.Should().Be(use2fa);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("user1", "pass123", "pass123", true)]
|
||||
[InlineData("", "", "", false)]
|
||||
[InlineData("testUser", null, null, true)]
|
||||
[InlineData(null, "pass123", "pass123", false)]
|
||||
public void ToCommand_WhenMappingRequestWithSpecificValues_ShouldMapCorrectly(
|
||||
string? username,
|
||||
string? password,
|
||||
string? passwordConfirm,
|
||||
bool use2fa)
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = new(username, password, passwordConfirm, use2fa);
|
||||
|
||||
// Act
|
||||
RegisterUserCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(username);
|
||||
result.Password.Should().Be(password);
|
||||
result.PasswordConfirm.Should().Be(passwordConfirm);
|
||||
result.Use2fa.Should().Be(use2fa);
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GenreDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GenreDtoMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidGenreDto_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GenreDto genreDto = new("Rock");
|
||||
|
||||
// Act
|
||||
ErrorOr<Genre> result = genreDto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Name.Should().Be(genreDto.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Rock")]
|
||||
[InlineData("Jazz")]
|
||||
[InlineData("Classical")]
|
||||
[InlineData("Pop")]
|
||||
public void ToDomainEntity_WhenMappingDifferentValidGenreDtos_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
GenreDto genreDto = new(name);
|
||||
|
||||
// Act
|
||||
ErrorOr<Genre> result = genreDto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Name.Should().Be(genreDto.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData(null)]
|
||||
public void ToDomainEntity_WhenMappingInvalidGenreDto_ShouldReturnError(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
GenreDto genreDto = new(invalidName);
|
||||
|
||||
// Act
|
||||
ErrorOr<Genre> result = genreDto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainModels_WhenMappingMultipleValidGenreDtos_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<GenreDto> genreDtos =
|
||||
[
|
||||
new GenreDto("Rock"),
|
||||
new GenreDto("Jazz"),
|
||||
new GenreDto("Classical"),
|
||||
new GenreDto("Pop")
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<Genre>> results = genreDtos.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(genreDtos.Count);
|
||||
|
||||
List<ErrorOr<Genre>> resultList = results.ToList();
|
||||
for (int i = 0; i < genreDtos.Count; i++)
|
||||
{
|
||||
resultList[i].IsError.Should().BeFalse();
|
||||
resultList[i].Value.Name.Should().Be(genreDtos[i].Name);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainModels_WhenMappingMixedValidAndInvalidGenreDtos_ShouldReturnMixedResults()
|
||||
{
|
||||
// Arrange
|
||||
List<GenreDto> genreDtos =
|
||||
[
|
||||
new GenreDto("Rock"),
|
||||
new GenreDto(""),
|
||||
new GenreDto("Jazz"),
|
||||
new GenreDto(" ")
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<Genre>> results = genreDtos.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(genreDtos.Count);
|
||||
|
||||
List<ErrorOr<Genre>> resultList = results.ToList();
|
||||
resultList[0].IsError.Should().BeFalse();
|
||||
resultList[0].Value.Name.Should().Be("Rock");
|
||||
|
||||
resultList[1].IsError.Should().BeTrue();
|
||||
|
||||
resultList[2].IsError.Should().BeFalse();
|
||||
resultList[2].Value.Name.Should().Be("Jazz");
|
||||
|
||||
resultList[3].IsError.Should().BeTrue();
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GenreEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GenreEntityMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidGenreEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = new("Fiction");
|
||||
|
||||
// Act
|
||||
GenreDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(entity.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Fiction")]
|
||||
[InlineData("Science Fiction")]
|
||||
[InlineData("Mystery")]
|
||||
[InlineData("Romance")]
|
||||
public void ToResponse_WhenMappingDifferentValidGenreEntities_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = new(name);
|
||||
|
||||
// Act
|
||||
GenreDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(entity.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData(null)]
|
||||
public void ToResponse_WhenMappingInvalidGenreEntity_ShouldMapToDefault(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = new(invalidName);
|
||||
|
||||
// Act
|
||||
GenreDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Name.Should().Be(invalidName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidGenreEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = new("Fiction");
|
||||
|
||||
// Act
|
||||
ErrorOr<Genre> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Name.Should().Be(entity.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData(null)]
|
||||
public void ToDomainEntity_WhenMappingInvalidGenreEntity_ShouldMapToDefault(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
GenreEntity entity = new(invalidName);
|
||||
|
||||
// Act
|
||||
ErrorOr<Genre> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Metadata.GenreNameCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleValidGenreEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<GenreEntity> entities =
|
||||
[
|
||||
new GenreEntity("Fiction"),
|
||||
new GenreEntity("Mystery"),
|
||||
new GenreEntity("Romance"),
|
||||
new GenreEntity("Thriller")
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<Genre>> results = entities.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(entities.Count);
|
||||
|
||||
List<ErrorOr<Genre>> resultList = results.ToList();
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
resultList[i].IsError.Should().BeFalse();
|
||||
resultList[i].Value.Name.Should().Be(entities[i].Name);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleValidGenreEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<GenreEntity> entities =
|
||||
[
|
||||
new GenreEntity("Fiction"),
|
||||
new GenreEntity("Mystery"),
|
||||
new GenreEntity("Romance"),
|
||||
new GenreEntity("Thriller")
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<GenreDto> results = entities.ToResponses();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(entities.Count);
|
||||
|
||||
List<GenreDto> resultList = results.ToList();
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
resultList[i].Name.Should().Be(entities[i].Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GenreMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GenreMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingGenre_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ErrorOr<Genre> createResult = Genre.Create("Rock");
|
||||
createResult.IsError.Should().BeFalse();
|
||||
Genre genre = createResult.Value;
|
||||
|
||||
// Act
|
||||
GenreEntity result = genre.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(genre.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Rock")]
|
||||
[InlineData("Jazz")]
|
||||
[InlineData("Classical")]
|
||||
[InlineData("Pop")]
|
||||
public void ToRepositoryEntity_WhenMappingDifferentGenres_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
ErrorOr<Genre> createResult = Genre.Create(name);
|
||||
createResult.IsError.Should().BeFalse();
|
||||
Genre genre = createResult.Value;
|
||||
|
||||
// Act
|
||||
GenreEntity result = genre.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(genre.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntities_WhenMappingMultipleGenres_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<Genre> genres =
|
||||
[
|
||||
Genre.Create("Rock").Value,
|
||||
Genre.Create("Jazz").Value,
|
||||
Genre.Create("Classical").Value,
|
||||
Genre.Create("Pop").Value
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<GenreEntity> results = genres.ToRepositoryEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(genres.Count);
|
||||
List<GenreEntity> resultList = results.ToList();
|
||||
for (int i = 0; i < genres.Count; i++)
|
||||
resultList[i].Name.Should().Be(genres[i].Name);
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TagDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TagDtoMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidTagDto_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TagDto tagDto = new("indie");
|
||||
|
||||
// Act
|
||||
ErrorOr<Tag> result = tagDto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Name.Should().Be(tagDto.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("indie")]
|
||||
[InlineData("electronic")]
|
||||
[InlineData("instrumental")]
|
||||
[InlineData("live")]
|
||||
[InlineData("acoustic")]
|
||||
public void ToDomainEntity_WhenMappingDifferentValidTagDtos_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
TagDto tagDto = new(name);
|
||||
|
||||
// Act
|
||||
ErrorOr<Tag> result = tagDto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Name.Should().Be(tagDto.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData(null)]
|
||||
public void ToDomainEntity_WhenMappingInvalidTagDto_ShouldReturnError(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
TagDto tagDto = new(invalidName);
|
||||
|
||||
// Act
|
||||
ErrorOr<Tag> result = tagDto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainModels_WhenMappingMultipleValidTagDtos_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<TagDto> tagDtos =
|
||||
[
|
||||
new TagDto("indie"),
|
||||
new TagDto("electronic"),
|
||||
new TagDto("instrumental"),
|
||||
new TagDto("live")
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<Tag>> results = tagDtos.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(tagDtos.Count);
|
||||
|
||||
List<ErrorOr<Tag>> resultList = results.ToList();
|
||||
for (int i = 0; i < tagDtos.Count; i++)
|
||||
{
|
||||
resultList[i].IsError.Should().BeFalse();
|
||||
resultList[i].Value.Name.Should().Be(tagDtos[i].Name);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainModels_WhenMappingMixedValidAndInvalidTagDtos_ShouldReturnMixedResults()
|
||||
{
|
||||
// Arrange
|
||||
List<TagDto> tagDtos =
|
||||
[
|
||||
new TagDto("indie"),
|
||||
new TagDto(""),
|
||||
new TagDto("electronic"),
|
||||
new TagDto(" ")
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<Tag>> results = tagDtos.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(tagDtos.Count);
|
||||
|
||||
List<ErrorOr<Tag>> resultList = results.ToList();
|
||||
resultList[0].IsError.Should().BeFalse();
|
||||
resultList[0].Value.Name.Should().Be("indie");
|
||||
|
||||
resultList[1].IsError.Should().BeTrue();
|
||||
|
||||
resultList[2].IsError.Should().BeFalse();
|
||||
resultList[2].Value.Name.Should().Be("electronic");
|
||||
|
||||
resultList[3].IsError.Should().BeTrue();
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TagEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TagEntityMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidTagEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = new("Fantasy");
|
||||
|
||||
// Act
|
||||
TagDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(entity.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Fantasy")]
|
||||
[InlineData("Young Adult")]
|
||||
[InlineData("Historical")]
|
||||
[InlineData("Coming of Age")]
|
||||
public void ToResponse_WhenMappingDifferentValidTagEntities_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = new(name);
|
||||
|
||||
// Act
|
||||
TagDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(entity.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData(null)]
|
||||
public void ToResponse_WhenMappingInvalidTagEntity_ShouldMapToDefault(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = new(invalidName);
|
||||
|
||||
// Act
|
||||
TagDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Name.Should().Be(invalidName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidTagEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = new("Fantasy");
|
||||
|
||||
// Act
|
||||
ErrorOr<Tag> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Name.Should().Be(entity.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData(null)]
|
||||
public void ToDomainEntity_WhenMappingInvalidTagEntity_ShouldMapToDefault(string? invalidName)
|
||||
{
|
||||
// Arrange
|
||||
TagEntity entity = new(invalidName);
|
||||
|
||||
// Act
|
||||
ErrorOr<Tag> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(Errors.Metadata.TagNameCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleValidTagEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> entities =
|
||||
[
|
||||
new TagEntity("Fantasy"),
|
||||
new TagEntity("Young Adult"),
|
||||
new TagEntity("Historical"),
|
||||
new TagEntity("Coming of Age")
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<Tag>> results = entities.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(entities.Count);
|
||||
|
||||
List<ErrorOr<Tag>> resultList = results.ToList();
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
resultList[i].IsError.Should().BeFalse();
|
||||
resultList[i].Value.Name.Should().Be(entities[i].Name);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleValidTagEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<TagEntity> entities =
|
||||
[
|
||||
new TagEntity("Fantasy"),
|
||||
new TagEntity("Young Adult"),
|
||||
new TagEntity("Historical"),
|
||||
new TagEntity("Coming of Age")
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<TagDto> results = entities.ToResponses();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(entities.Count);
|
||||
|
||||
List<TagDto> resultList = results.ToList();
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
resultList[i].Name.Should().Be(entities[i].Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TagMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TagMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingTag_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ErrorOr<Tag> createResult = Tag.Create("indie");
|
||||
createResult.IsError.Should().BeFalse();
|
||||
Tag tag = createResult.Value;
|
||||
|
||||
// Act
|
||||
TagEntity result = tag.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(tag.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("indie")]
|
||||
[InlineData("electronic")]
|
||||
[InlineData("instrumental")]
|
||||
[InlineData("live")]
|
||||
[InlineData("acoustic")]
|
||||
public void ToRepositoryEntity_WhenMappingDifferentTags_ShouldMapCorrectly(string name)
|
||||
{
|
||||
// Arrange
|
||||
ErrorOr<Tag> createResult = Tag.Create(name);
|
||||
createResult.IsError.Should().BeFalse();
|
||||
Tag tag = createResult.Value;
|
||||
|
||||
// Act
|
||||
TagEntity result = tag.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(tag.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntities_WhenMappingMultipleTags_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<Tag> tags =
|
||||
[
|
||||
Tag.Create("indie").Value,
|
||||
Tag.Create("electronic").Value,
|
||||
Tag.Create("instrumental").Value,
|
||||
Tag.Create("live").Value,
|
||||
Tag.Create("acoustic").Value
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<TagEntity> results = tags.ToRepositoryEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(tags.Count);
|
||||
List<TagEntity> resultList = results.ToList();
|
||||
for (int i = 0; i < tags.Count; i++)
|
||||
resultList[i].Name.Should().Be(tags[i].Name);
|
||||
}
|
||||
}
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileManagement;
|
||||
using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures;
|
||||
using Lumina.Contracts.Models.FileManagement;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
|
||||
using Mapster;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DirectoryMappingConfig"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DirectoryMappingConfigTests
|
||||
{
|
||||
private readonly TypeAdapterConfig _config;
|
||||
private readonly DirectoryMappingConfig _directoryMappingConfig;
|
||||
private readonly FileSystemTreeMappingConfig _fileSystemTreeMappingConfig;
|
||||
|
||||
public DirectoryMappingConfigTests()
|
||||
{
|
||||
_config = new TypeAdapterConfig();
|
||||
_directoryMappingConfig = new DirectoryMappingConfig();
|
||||
_fileSystemTreeMappingConfig = new FileSystemTreeMappingConfig();
|
||||
_directoryMappingConfig.Register(_config);
|
||||
_fileSystemTreeMappingConfig.Register(_config);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingDirectoryToFileSystemTreeNodeResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
DirectoryFixture directoryFixture = new();
|
||||
Directory directory = directoryFixture.CreateDirectory();
|
||||
|
||||
// create some child items
|
||||
List<FileSystemItem> childItems =
|
||||
[
|
||||
directoryFixture.CreateDirectory(),
|
||||
directoryFixture.CreateDirectory()
|
||||
];
|
||||
foreach (FileSystemItem item in childItems)
|
||||
directory.AddItem(item);
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = directory.Adapt<FileSystemTreeNodeResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(directory.Name);
|
||||
result.Path.Should().Be(directory.Id.Path);
|
||||
result.ItemType.Should().Be(directory.Type);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().NotBeNull();
|
||||
result.Children.Should().HaveCount(childItems.Count);
|
||||
|
||||
// Verify that each child item is correctly mapped
|
||||
for (int i = 0; i < childItems.Count; i++)
|
||||
{
|
||||
result.Children[i].Name.Should().Be(childItems[i].Name);
|
||||
result.Children[i].Path.Should().Be(childItems[i].Id.Path);
|
||||
result.Children[i].ItemType.Should().Be(childItems[i].Type);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingDirectoryToDirectoryResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
DirectoryFixture directoryFixture = new();
|
||||
Directory directory = directoryFixture.CreateDirectory();
|
||||
|
||||
// Act
|
||||
DirectoryResponse result = directory.Adapt<DirectoryResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(directory.Id.Path);
|
||||
result.Name.Should().Be(directory.Name);
|
||||
result.DateCreated.Should().Be(directory.DateCreated.Value);
|
||||
result.DateModified.Should().Be(directory.DateModified.Value);
|
||||
result.Items.Should().BeAssignableTo<List<FileSystemItemModel>>();
|
||||
result.Items.Should().HaveCount(directory.Items.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingDirectoryToFileSystemItemModel_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
DirectoryFixture directoryFixture = new();
|
||||
Directory directory = directoryFixture.CreateDirectory();
|
||||
DateTime beforeMapping = DateTime.Now;
|
||||
|
||||
// Act
|
||||
FileSystemItemModel result = directory.Adapt<FileSystemItemModel>(_config);
|
||||
DateTime afterMapping = DateTime.Now;
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(directory.Id.Path);
|
||||
result.Name.Should().Be(directory.Name);
|
||||
result.DateCreated.Should().BeOnOrAfter(beforeMapping).And.BeOnOrBefore(afterMapping);
|
||||
result.DateModified.Should().BeOnOrAfter(beforeMapping).And.BeOnOrBefore(afterMapping);
|
||||
}
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileManagement;
|
||||
using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
|
||||
using Mapster;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileMappingConfig"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileMappingConfigTests
|
||||
{
|
||||
private readonly TypeAdapterConfig _config;
|
||||
private readonly FileMappingConfig _fileMappingConfig;
|
||||
private readonly FileSystemTreeMappingConfig _fileSystemTreeMappingConfig;
|
||||
|
||||
public FileMappingConfigTests()
|
||||
{
|
||||
_config = new TypeAdapterConfig();
|
||||
_fileMappingConfig = new FileMappingConfig();
|
||||
_fileSystemTreeMappingConfig = new FileSystemTreeMappingConfig();
|
||||
_fileMappingConfig.Register(_config);
|
||||
_fileSystemTreeMappingConfig.Register(_config);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingFileToFileSystemTreeNodeResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileFixture fileFixture = new();
|
||||
File file = fileFixture.CreateFile();
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = file.Adapt<FileSystemTreeNodeResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(file.Name);
|
||||
result.Path.Should().Be(file.Id.Path);
|
||||
result.ItemType.Should().Be(file.Type);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingFileToFileResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileFixture fileFixture = new();
|
||||
File file = fileFixture.CreateFile();
|
||||
|
||||
// Act
|
||||
FileResponse result = file.Adapt<FileResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(file.Id.Path);
|
||||
result.Name.Should().Be(file.Name);
|
||||
result.DateCreated.Should().Be(file.DateCreated.Value);
|
||||
result.DateModified.Should().Be(file.DateModified.Value);
|
||||
result.Size.Should().Be(file.Size);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingFileToFileResponseWithoutDates_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileFixture fileFixture = new();
|
||||
File file = FileFixture.CreateFileWithoutDates();
|
||||
|
||||
// Act
|
||||
FileResponse result = file.Adapt<FileResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(file.Id.Path);
|
||||
result.Name.Should().Be(file.Name);
|
||||
result.DateCreated.Should().Be(default);
|
||||
result.DateModified.Should().Be(default);
|
||||
result.Size.Should().Be(file.Size);
|
||||
}
|
||||
}
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileManagement;
|
||||
using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
|
||||
using Mapster;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileSystemTreeMappingConfig"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemTreeMappingConfigTests
|
||||
{
|
||||
private readonly TypeAdapterConfig _config;
|
||||
private readonly FileSystemTreeMappingConfig _fileSystemTreeMappingConfig;
|
||||
|
||||
public FileSystemTreeMappingConfigTests()
|
||||
{
|
||||
_config = new TypeAdapterConfig();
|
||||
_fileSystemTreeMappingConfig = new FileSystemTreeMappingConfig();
|
||||
_fileSystemTreeMappingConfig.Register(_config);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingWindowsRootItemToFileSystemTreeNodeResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
WindowsRootItem windowsRoot = WindowsRootItem.Create("C:", "C:").Value;
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = windowsRoot.Adapt<FileSystemTreeNodeResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(windowsRoot.Id.Path);
|
||||
result.Name.Should().Be(windowsRoot.Name);
|
||||
result.ItemType.Should().Be(FileSystemItemType.Root);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.Children.Should().NotBeNull();
|
||||
result.Children.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingFileSystemTreeNodeResponseToWindowsRootItem_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemTreeNodeResponse response = new()
|
||||
{
|
||||
Path = "D:",
|
||||
Name = "D:",
|
||||
ItemType = FileSystemItemType.Root,
|
||||
IsExpanded = false
|
||||
};
|
||||
|
||||
// Act
|
||||
WindowsRootItem result = response.Adapt<WindowsRootItem>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Id.Path.Should().Be(response.Path);
|
||||
result.Name.Should().Be(response.Name);
|
||||
result.Type.Should().Be(FileSystemItemType.Root);
|
||||
result.Status.Should().Be(FileSystemItemStatus.Accessible);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingUnixRootItemToFileSystemTreeNodeResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
UnixRootItem unixRoot = UnixRootItem.Create().Value;
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = unixRoot.Adapt<FileSystemTreeNodeResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(unixRoot.Id.Path);
|
||||
result.Name.Should().Be(unixRoot.Name);
|
||||
result.ItemType.Should().Be(FileSystemItemType.Root);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().NotBeNull();
|
||||
result.Children.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingFileSystemTreeNodeResponseToUnixRootItem_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemTreeNodeResponse response = new()
|
||||
{
|
||||
Path = "/",
|
||||
Name = "/",
|
||||
ItemType = FileSystemItemType.Root,
|
||||
IsExpanded = false
|
||||
};
|
||||
|
||||
// Act
|
||||
UnixRootItem result = response.Adapt<UnixRootItem>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Id.Path.Should().Be("/");
|
||||
result.Name.Should().Be("/");
|
||||
result.Type.Should().Be(FileSystemItemType.Root);
|
||||
result.Status.Should().Be(FileSystemItemStatus.Accessible);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingDirectoryToFileSystemTreeNodeResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
DirectoryFixture directoryFixture = new();
|
||||
Directory directory = directoryFixture.CreateDirectory();
|
||||
directory.AddItem(directoryFixture.CreateDirectory());
|
||||
directory.AddItem(directoryFixture.CreateDirectory());
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = directory.Adapt<FileSystemTreeNodeResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(directory.Name);
|
||||
result.Path.Should().Be(directory.Id.Path);
|
||||
result.ItemType.Should().Be(directory.Type);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().NotBeNull();
|
||||
result.Children.Should().HaveCount(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingFileToFileSystemTreeNodeResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileFixture fileFixture = new();
|
||||
File file = fileFixture.CreateFile();
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = file.Adapt<FileSystemTreeNodeResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(file.Name);
|
||||
result.Path.Should().Be(file.Id.Path);
|
||||
result.ItemType.Should().Be(file.Type);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
-109
@@ -1,109 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileManagement;
|
||||
using Lumina.Contracts.Enums.PhotoLibrary;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
|
||||
using Mapster;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThumbnailMappingConfig"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThumbnailMappingConfigTests
|
||||
{
|
||||
private readonly TypeAdapterConfig _config;
|
||||
private readonly ThumbnailMappingConfig _thumbnailMappingConfig;
|
||||
private readonly Faker _faker;
|
||||
|
||||
public ThumbnailMappingConfigTests()
|
||||
{
|
||||
_config = new TypeAdapterConfig();
|
||||
_thumbnailMappingConfig = new ThumbnailMappingConfig();
|
||||
_thumbnailMappingConfig.Register(_config);
|
||||
_faker = new Faker();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingThumbnailToThumbnailResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ImageType imageType = _faker.PickRandom<ImageType>();
|
||||
byte[] bytes = _faker.Random.Bytes(100);
|
||||
Thumbnail thumbnail = new(imageType, bytes);
|
||||
|
||||
// Act
|
||||
ThumbnailResponse result = thumbnail.Adapt<ThumbnailResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Type.Should().Be(thumbnail.Type);
|
||||
result.Bytes.Should().BeEquivalentTo(thumbnail.Bytes);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ImageType.JPEG)]
|
||||
[InlineData(ImageType.PNG)]
|
||||
[InlineData(ImageType.GIF)]
|
||||
public void Register_WhenMappingDifferentImageTypes_ShouldMapCorrectly(ImageType imageType)
|
||||
{
|
||||
// Arrange
|
||||
byte[] bytes = _faker.Random.Bytes(100);
|
||||
Thumbnail thumbnail = new(imageType, bytes);
|
||||
|
||||
// Act
|
||||
ThumbnailResponse result = thumbnail.Adapt<ThumbnailResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Type.Should().Be(imageType);
|
||||
result.Bytes.Should().BeEquivalentTo(bytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingThumbnailWithEmptyBytes_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ImageType imageType = _faker.PickRandom<ImageType>();
|
||||
byte[] emptyBytes = [];
|
||||
Thumbnail thumbnail = new(imageType, emptyBytes);
|
||||
|
||||
// Act
|
||||
ThumbnailResponse result = thumbnail.Adapt<ThumbnailResponse>(_config);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Type.Should().Be(imageType);
|
||||
result.Bytes.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingMultipleThumbnails_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<Thumbnail> thumbnails =
|
||||
[
|
||||
new Thumbnail(ImageType.JPEG, _faker.Random.Bytes(100)),
|
||||
new Thumbnail(ImageType.PNG, _faker.Random.Bytes(200)),
|
||||
new Thumbnail(ImageType.GIF, _faker.Random.Bytes(150))
|
||||
];
|
||||
|
||||
// Act
|
||||
List<ThumbnailResponse> results = thumbnails.Adapt<List<ThumbnailResponse>>(_config);
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(thumbnails.Count);
|
||||
for (int i = 0; i < thumbnails.Count; i++)
|
||||
{
|
||||
results[i].Type.Should().Be(thumbnails[i].Type);
|
||||
results[i].Bytes.Should().BeEquivalentTo(thumbnails[i].Bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Common;
|
||||
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
|
||||
using Lumina.Domain.Common.Enums.FileSystem;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileSystemTreeNodeResponseMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemTreeNodeResponseMappingTests
|
||||
{
|
||||
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemTreeNodeResponseMappingTests"/> class.
|
||||
/// </summary>
|
||||
public FileSystemTreeNodeResponseMappingTests()
|
||||
{
|
||||
_fileSystemTreeNodeResponseFixture = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToWindowsRootItem_WhenMappingFileSystemTreeNodeResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemTreeNodeResponse response = _fileSystemTreeNodeResponseFixture.Create();
|
||||
|
||||
// Act
|
||||
ErrorOr<WindowsRootItem> result = response.ToWindowsRootItem();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Id.Path.Should().Be(response.Path);
|
||||
result.Value.Name.Should().Be(response.Name);
|
||||
result.Value.Status.Should().Be(FileSystemItemStatus.Accessible);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToUnixRootItem_WhenMappingFileSystemTreeNodeResponse_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemTreeNodeResponse response = _fileSystemTreeNodeResponseFixture.Create();
|
||||
|
||||
// Act
|
||||
ErrorOr<UnixRootItem> result = response.ToUnixRootItem();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Status.Should().Be(FileSystemItemStatus.Accessible);
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
|
||||
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Directories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DirectoryMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DirectoryMappingTests
|
||||
{
|
||||
private readonly DirectoryFixture _directoryFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DirectoryMappingTests"/> class.
|
||||
/// </summary>
|
||||
public DirectoryMappingTests()
|
||||
{
|
||||
_directoryFixture = new DirectoryFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToFileSystemTreeNodeResponse_WhenMappingDirectory_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Directory directory = _directoryFixture.CreateDirectory();
|
||||
List<FileSystemItem> childItems =
|
||||
[
|
||||
_directoryFixture.CreateDirectory(),
|
||||
_directoryFixture.CreateDirectory()
|
||||
];
|
||||
foreach (FileSystemItem item in childItems)
|
||||
directory.AddItem(item);
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = directory.ToFileSystemTreeNodeResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(directory.Name);
|
||||
result.Path.Should().Be(directory.Id.Path);
|
||||
result.ItemType.Should().Be(directory.Type);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().NotBeNull();
|
||||
result.Children.Should().HaveCount(childItems.Count);
|
||||
|
||||
for (int i = 0; i < childItems.Count; i++)
|
||||
{
|
||||
result.Children[i].Name.Should().Be(childItems[i].Name);
|
||||
result.Children[i].Path.Should().Be(childItems[i].Id.Path);
|
||||
result.Children[i].ItemType.Should().Be(childItems[i].Type);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToFileSystemTreeNodeResponses_WhenMappingMultipleDirectories_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<Directory> directories = _directoryFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
IEnumerable<FileSystemTreeNodeResponse> result = directories.ToFileSystemTreeNodeResponses();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Should().HaveCount(directories.Count);
|
||||
|
||||
List<FileSystemTreeNodeResponse> resultList = result.ToList();
|
||||
for (int i = 0; i < directories.Count; i++)
|
||||
{
|
||||
resultList[i].Name.Should().Be(directories[i].Name);
|
||||
resultList[i].Path.Should().Be(directories[i].Id.Path);
|
||||
resultList[i].ItemType.Should().Be(directories[i].Type);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingDirectory_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Directory directory = _directoryFixture.CreateDirectory();
|
||||
List<FileSystemItem> childItems =
|
||||
[
|
||||
_directoryFixture.CreateDirectory(),
|
||||
_directoryFixture.CreateDirectory()
|
||||
];
|
||||
foreach (FileSystemItem item in childItems)
|
||||
directory.AddItem(item);
|
||||
|
||||
// Act
|
||||
DirectoryResponse result = directory.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(directory.Id.Path);
|
||||
result.Name.Should().Be(directory.Name);
|
||||
result.DateCreated.Should().Be(directory.DateCreated.Value);
|
||||
result.DateModified.Should().Be(directory.DateModified.Value);
|
||||
result.Items.Should().NotBeNull();
|
||||
result.Items.Should().HaveCount(childItems.Count);
|
||||
|
||||
for (int i = 0; i < childItems.Count; i++)
|
||||
{
|
||||
result.Items[i].Name.Should().Be(childItems[i].Name);
|
||||
result.Items[i].Path.Should().Be(childItems[i].Id.Path);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleDirectories_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<Directory> directories = _directoryFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
IEnumerable<DirectoryResponse> result = directories.ToResponses();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Should().HaveCount(directories.Count);
|
||||
|
||||
List<DirectoryResponse> resultList = result.ToList();
|
||||
for (int i = 0; i < directories.Count; i++)
|
||||
{
|
||||
resultList[i].Path.Should().Be(directories[i].Id.Path);
|
||||
resultList[i].Name.Should().Be(directories[i].Name);
|
||||
resultList[i].DateCreated.Should().Be(directories[i].DateCreated.Value);
|
||||
resultList[i].DateModified.Should().Be(directories[i].DateModified.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
|
||||
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Directories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetDirectoriesRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoriesRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDirectoriesRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetDirectoriesRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingGetDirectoriesRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoriesRequest request = _fixture.Create<GetDirectoriesRequest>();
|
||||
|
||||
// Act
|
||||
GetDirectoriesQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
|
||||
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectoryTree;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Directories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetDirectoryTreeRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetDirectoryTreeRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetDirectoryTreeRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetDirectoryTreeRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingGetDirectoryTreeRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetDirectoryTreeRequest request = _fixture.Create<GetDirectoryTreeRequest>();
|
||||
|
||||
// Act
|
||||
GetDirectoryTreeQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
result.IncludeFiles.Should().Be(request.IncludeFiles);
|
||||
result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
|
||||
using Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetTreeDirectories;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Directories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTreeDirectoriesRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTreeDirectoriesRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTreeDirectoriesRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetTreeDirectoriesRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingGetTreeDirectoriesRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesRequest request = _fixture.Create<GetTreeDirectoriesRequest>();
|
||||
|
||||
// Act
|
||||
GetTreeDirectoriesQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements);
|
||||
}
|
||||
}
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem;
|
||||
using Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.FileSystemManagement.FileSystem.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.FileSystemManagement.Fixtures;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Domain.Common.Enums.FileSystem;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using Lumina.Contracts.DTO.FileSystemManagement;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileSystemItemMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemItemMappingTests
|
||||
{
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture;
|
||||
private readonly DirectoryFixture _directoryFixture;
|
||||
private readonly FileFixture _fileFixture;
|
||||
private readonly WindowsRootItemFixture _windowsRootItemFixture;
|
||||
private readonly UnixRootItemFixture _unixRootItemFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemItemMappingTests"/> class.
|
||||
/// </summary>
|
||||
public FileSystemItemMappingTests()
|
||||
{
|
||||
_fileSystemPathIdFixture = new FileSystemPathIdFixture();
|
||||
_directoryFixture = new DirectoryFixture();
|
||||
_fileFixture = new FileFixture();
|
||||
_windowsRootItemFixture = new WindowsRootItemFixture();
|
||||
_unixRootItemFixture = new UnixRootItemFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToFileSystemItemModel_WhenMappingFileSystemItem_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId();
|
||||
string name = "TestItem";
|
||||
FileSystemItemType type = FileSystemItemType.File;
|
||||
FileSystemItemFixture domainModel = new(id, name, type);
|
||||
|
||||
// Arrange
|
||||
|
||||
// Act
|
||||
FileSystemItemDto result = domainModel.ToFileSystemItemDto();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(domainModel.Id.Path);
|
||||
result.Name.Should().Be(domainModel.Name);
|
||||
result.DateCreated.Should().BeCloseTo(DateTime.Now, TimeSpan.FromSeconds(1));
|
||||
result.DateModified.Should().BeCloseTo(DateTime.Now, TimeSpan.FromSeconds(1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToTreeNodeResponse_WhenMappingDirectory_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Directory directory = _directoryFixture.CreateDirectory();
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = directory.ToTreeNodeResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(directory.Name);
|
||||
result.Path.Should().Be(directory.Id.Path);
|
||||
result.ItemType.Should().Be(directory.Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToTreeNodeResponse_WhenMappingFile_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
File file = _fileFixture.CreateFile();
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = file.ToTreeNodeResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(file.Name);
|
||||
result.Path.Should().Be(file.Id.Path);
|
||||
result.ItemType.Should().Be(file.Type);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToTreeNodeResponse_WhenMappingWindowsRootItem_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
WindowsRootItem windowsRootItem = _windowsRootItemFixture.Create();
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = windowsRootItem.ToTreeNodeResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(windowsRootItem.Name);
|
||||
result.Path.Should().Be(windowsRootItem.Id.Path);
|
||||
result.ItemType.Should().Be(windowsRootItem.Type);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToTreeNodeResponse_WhenMappingUnixRootItem_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
UnixRootItem unixRootItem = _unixRootItemFixture.Create();
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = unixRootItem.ToTreeNodeResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(unixRootItem.Name);
|
||||
result.Path.Should().Be(unixRootItem.Id.Path);
|
||||
result.ItemType.Should().Be(unixRootItem.Type);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("TestFile.txt", FileSystemItemType.File)]
|
||||
[InlineData("TestFolder", FileSystemItemType.Directory)]
|
||||
public void ToFileSystemItemModel_WhenMappingDifferentFileSystemItems_ShouldMapCorrectly(string name, FileSystemItemType type)
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId();
|
||||
FileSystemItemFixture domainModel = new(id, name, type);
|
||||
|
||||
// Act
|
||||
FileSystemItemDto result = domainModel.ToFileSystemItemDto();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(domainModel.Id.Path);
|
||||
result.Name.Should().Be(domainModel.Name);
|
||||
result.DateCreated.Should().BeCloseTo(DateTime.Now, TimeSpan.FromSeconds(1));
|
||||
result.DateModified.Should().BeCloseTo(DateTime.Now, TimeSpan.FromSeconds(1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToTreeNodeResponses_WhenMappingMixedFileSystemItems_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<FileSystemItem> domainModels =
|
||||
[
|
||||
_directoryFixture.CreateDirectory(),
|
||||
_fileFixture.CreateFile(),
|
||||
_windowsRootItemFixture.Create(),
|
||||
_unixRootItemFixture.Create()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<FileSystemTreeNodeResponse> result = domainModels.ToTreeNodeResponses();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Should().HaveCount(domainModels.Count);
|
||||
|
||||
List<FileSystemTreeNodeResponse> resultList = result.ToList();
|
||||
for (int i = 0; i < resultList.Count; i++)
|
||||
{
|
||||
resultList[i].Name.Should().Be(domainModels[i].Name);
|
||||
resultList[i].Path.Should().Be(domainModels[i].Id.Path);
|
||||
resultList[i].ItemType.Should().Be(domainModels[i].Type);
|
||||
resultList[i].IsExpanded.Should().BeFalse();
|
||||
resultList[i].ChildrenLoaded.Should().BeFalse();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToTreeNodeResponse_WhenMappingInvalidFileSystemItem_ShouldThrowArgumentException()
|
||||
{
|
||||
// Arrange
|
||||
FileSystemPathId id = _fileSystemPathIdFixture.CreateFileSystemPathId();
|
||||
string name = "TestItem";
|
||||
FileSystemItemType type = FileSystemItemType.File;
|
||||
FileSystemItemFixture invalidItem = new(id, name, type);
|
||||
|
||||
// Act & Assert
|
||||
invalidItem.Invoking(item => item.ToTreeNodeResponse())
|
||||
.Should().Throw<ArgumentException>()
|
||||
.WithMessage("Invalid FileSystemItem");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToTreeNodeResponses_WhenMappingMultipleFileSystemItems_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IEnumerable<FileSystemItem> domainModels = _directoryFixture.CreateMany();
|
||||
|
||||
// Act
|
||||
IEnumerable<FileSystemTreeNodeResponse> result = domainModels.ToTreeNodeResponses();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Should().HaveCount(domainModels.Count());
|
||||
|
||||
List<FileSystemTreeNodeResponse> resultList = result.ToList();
|
||||
List<FileSystemItem> domainModelsList = domainModels.ToList();
|
||||
for (int i = 0; i < resultList.Count; i++)
|
||||
{
|
||||
resultList[i].Name.Should().Be(domainModelsList[i].Name);
|
||||
resultList[i].Path.Should().Be(domainModelsList[i].Id.Path);
|
||||
resultList[i].ItemType.Should().Be(domainModelsList[i].Type);
|
||||
resultList[i].IsExpanded.Should().BeFalse();
|
||||
resultList[i].ChildrenLoaded.Should().BeFalse();
|
||||
resultList[i].Children.Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Enums.FileSystem;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="FileSystemItem"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileSystemItemFixture : FileSystemItem
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemItemFixture"/> class.
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier for the file system path.</param>
|
||||
/// <param name="name">The name of the file system item.</param>
|
||||
/// <param name="fileSystemItemType">The type of the file system item.</param>
|
||||
public FileSystemItemFixture(FileSystemPathId id, string name, FileSystemItemType fileSystemItemType)
|
||||
: base(id, name, fileSystemItemType)
|
||||
{
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem;
|
||||
using Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
|
||||
using Lumina.Domain.Common.Enums.FileSystem;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UnixRootItemMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UnixRootItemMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToTreeNodeResponse_WhenMappingUnixRootItem_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ErrorOr<UnixRootItem> createResult = UnixRootItem.Create();
|
||||
createResult.IsError.Should().BeFalse();
|
||||
UnixRootItem domainModel = createResult.Value;
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = domainModel.ToTreeNodeResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(domainModel.Id.Path);
|
||||
result.Name.Should().Be(domainModel.Name);
|
||||
result.ItemType.Should().Be(FileSystemItemType.Root);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().NotBeNull();
|
||||
result.Children.Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem;
|
||||
using Lumina.Domain.Common.Enums.FileSystem;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileSystem;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="WindowsRootItemMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class WindowsRootItemMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToTreeNodeResponse_WhenMappingWindowsRootItem_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
string path = "C:\\";
|
||||
string name = "C:";
|
||||
ErrorOr<WindowsRootItem> createResult = WindowsRootItem.Create(path, name);
|
||||
createResult.IsError.Should().BeFalse();
|
||||
WindowsRootItem domainModel = createResult.Value;
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = domainModel.ToTreeNodeResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(domainModel.Id.Path);
|
||||
result.Name.Should().Be(domainModel.Name);
|
||||
result.ItemType.Should().Be(FileSystemItemType.Root);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToTreeNodeResponse_WhenMappingWindowsRootItemWithCustomStatus_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
string path = "D:\\";
|
||||
string name = "D:";
|
||||
FileSystemItemStatus customStatus = FileSystemItemStatus.Inaccessible;
|
||||
ErrorOr<WindowsRootItem> createResult = WindowsRootItem.Create(path, name, customStatus);
|
||||
createResult.IsError.Should().BeFalse();
|
||||
WindowsRootItem domainModel = createResult.Value;
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = domainModel.ToTreeNodeResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(domainModel.Id.Path);
|
||||
result.Name.Should().Be(domainModel.Name);
|
||||
result.ItemType.Should().Be(FileSystemItemType.Root);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
result.Children.Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
|
||||
using Lumina.Application.UnitTests.Core.FileSystemManagement.Files.Fixtures;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Files;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="FileMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FileMappingTests
|
||||
{
|
||||
private readonly FileFixture _fileFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileMappingTests"/> class.
|
||||
/// </summary>
|
||||
public FileMappingTests()
|
||||
{
|
||||
_fileFixture = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToFileSystemTreeNodeResponse_WhenMappingFile_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
File domainModel = _fileFixture.CreateFile();
|
||||
|
||||
// Act
|
||||
FileSystemTreeNodeResponse result = domainModel.ToFileSystemTreeNodeResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Name.Should().Be(domainModel.Name);
|
||||
result.Path.Should().Be(domainModel.Id.Path);
|
||||
result.ItemType.Should().Be(domainModel.Type);
|
||||
result.IsExpanded.Should().BeFalse();
|
||||
result.ChildrenLoaded.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToFileSystemTreeNodeResponses_WhenMappingMultipleFiles_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IEnumerable<File> domainModels = _fileFixture.CreateMany();
|
||||
|
||||
// Act
|
||||
IEnumerable<FileSystemTreeNodeResponse> result = domainModels.ToFileSystemTreeNodeResponses();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Should().HaveCount(domainModels.Count());
|
||||
|
||||
List<FileSystemTreeNodeResponse> resultList = result.ToList();
|
||||
List<File> domainModelsList = domainModels.ToList();
|
||||
for (int i = 0; i < resultList.Count; i++)
|
||||
{
|
||||
resultList[i].Name.Should().Be(domainModelsList[i].Name);
|
||||
resultList[i].Path.Should().Be(domainModelsList[i].Id.Path);
|
||||
resultList[i].ItemType.Should().Be(domainModelsList[i].Type);
|
||||
resultList[i].IsExpanded.Should().BeFalse();
|
||||
resultList[i].ChildrenLoaded.Should().BeFalse();
|
||||
resultList[i].Children.Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingFile_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
File domainModel = _fileFixture.CreateFile();
|
||||
|
||||
// Act
|
||||
FileResponse result = domainModel.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(domainModel.Id.Path);
|
||||
result.Name.Should().Be(domainModel.Name);
|
||||
result.DateCreated.Should().Be(domainModel.DateCreated.Value);
|
||||
result.DateModified.Should().Be(domainModel.DateModified.Value);
|
||||
result.Size.Should().Be(domainModel.Size);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleFiles_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IEnumerable<File> domainModels = _fileFixture.CreateMany();
|
||||
|
||||
// Act
|
||||
IEnumerable<FileResponse> result = domainModels.ToResponses();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Should().HaveCount(domainModels.Count());
|
||||
|
||||
List<FileResponse> resultList = result.ToList();
|
||||
List<File> domainModelsList = domainModels.ToList();
|
||||
for (int i = 0; i < resultList.Count; i++)
|
||||
{
|
||||
resultList[i].Name.Should().Be(domainModelsList[i].Name);
|
||||
resultList[i].Path.Should().Be(domainModelsList[i].Id.Path);
|
||||
resultList[i].Size.Should().Be(domainModelsList[i].Size);
|
||||
resultList[i].DateCreated.Should().Be(domainModelsList[i].DateCreated.Value);
|
||||
resultList[i].DateModified.Should().Be(domainModelsList[i].DateModified.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
|
||||
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Files;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFilesRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFilesRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFilesRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetFilesRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingGetFilesRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetFilesRequest request = _fixture.Create<GetFilesRequest>();
|
||||
|
||||
// Act
|
||||
GetFilesQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
|
||||
using Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Files;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTreeFilesRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTreeFilesRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTreeFilesRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetTreeFilesRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingGetTreeFilesRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeFilesRequest request = _fixture.Create<GetTreeFilesRequest>();
|
||||
|
||||
// Act
|
||||
GetTreeFilesQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CheckPathExistsRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CheckPathExistsRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckPathExistsRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public CheckPathExistsRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingCheckPathExistsRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
CheckPathExistsRequest request = _fixture.Create<CheckPathExistsRequest>();
|
||||
|
||||
// Act
|
||||
CheckPathExistsQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
result.IncludeHiddenElements.Should().Be(request.IncludeHiddenElements);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/home/user/documents", true)]
|
||||
[InlineData("C:\\Users\\Documents", false)]
|
||||
[InlineData("/var/www/html", true)]
|
||||
public void ToQuery_WhenMappingWithDifferentPathsAndHiddenElementsFlag_ShouldMapCorrectly(string path, bool includeHiddenElements)
|
||||
{
|
||||
// Arrange
|
||||
CheckPathExistsRequest request = new(path, includeHiddenElements);
|
||||
|
||||
// Act
|
||||
CheckPathExistsQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(path);
|
||||
result.IncludeHiddenElements.Should().Be(includeHiddenElements);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<CheckPathExistsRequest> requests = _fixture.CreateMany<CheckPathExistsRequest>().ToList();
|
||||
|
||||
// Act
|
||||
List<CheckPathExistsQuery> results = requests.Select(r => r.ToQuery()).ToList();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(requests.Count);
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
{
|
||||
results[i].Path.Should().Be(requests[i].Path);
|
||||
results[i].IncludeHiddenElements.Should().Be(requests[i].IncludeHiddenElements);
|
||||
}
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CombinePathRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CombinePathRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CombinePathRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public CombinePathRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingCombinePathRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
CombinePathRequest request = _fixture.Create<CombinePathRequest>();
|
||||
|
||||
// Act
|
||||
CombinePathCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.OriginalPath.Should().Be(request.OriginalPath);
|
||||
result.NewPath.Should().Be(request.NewPath);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/home/user", "documents")]
|
||||
[InlineData("C:\\Users", "Documents")]
|
||||
[InlineData("/var/www", "html")]
|
||||
public void ToCommand_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string originalPath, string newPath)
|
||||
{
|
||||
// Arrange
|
||||
CombinePathRequest request = new(originalPath, newPath);
|
||||
|
||||
// Act
|
||||
CombinePathCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.OriginalPath.Should().Be(originalPath);
|
||||
result.NewPath.Should().Be(newPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<CombinePathRequest> requests = _fixture.CreateMany<CombinePathRequest>().ToList();
|
||||
|
||||
// Act
|
||||
List<CombinePathCommand> results = requests.Select(r => r.ToCommand()).ToList();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(requests.Count);
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
{
|
||||
results[i].OriginalPath.Should().Be(requests[i].OriginalPath);
|
||||
results[i].NewPath.Should().Be(requests[i].NewPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPathParentRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathParentRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathParentRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetPathParentRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingGetPathParentRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentRequest request = _fixture.Create<GetPathParentRequest>();
|
||||
|
||||
// Act
|
||||
GetPathParentQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/home/user/documents")]
|
||||
[InlineData("C:\\Users\\Documents")]
|
||||
[InlineData("/var/www/html")]
|
||||
public void ToQuery_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path)
|
||||
{
|
||||
// Arrange
|
||||
GetPathParentRequest request = new(path);
|
||||
|
||||
// Act
|
||||
GetPathParentQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<GetPathParentRequest> requests = _fixture.CreateMany<GetPathParentRequest>().ToList();
|
||||
|
||||
// Act
|
||||
List<GetPathParentQuery> results = requests.Select(r => r.ToQuery()).ToList();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(requests.Count);
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
{
|
||||
results[i].Path.Should().Be(requests[i].Path);
|
||||
}
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetPathRootRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPathRootRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPathRootRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetPathRootRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingGetPathRootRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetPathRootRequest request = _fixture.Create<GetPathRootRequest>();
|
||||
|
||||
// Act
|
||||
GetPathRootQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/home/user/documents")]
|
||||
[InlineData("C:\\Users\\Documents")]
|
||||
[InlineData("/var/www/html")]
|
||||
[InlineData("D:\\Projects\\MyProject")]
|
||||
public void ToQuery_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path)
|
||||
{
|
||||
// Arrange
|
||||
GetPathRootRequest request = new(path);
|
||||
|
||||
// Act
|
||||
GetPathRootQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<GetPathRootRequest> requests = _fixture.CreateMany<GetPathRootRequest>().ToList();
|
||||
|
||||
// Act
|
||||
List<GetPathRootQuery> results = requests.Select(r => r.ToQuery()).ToList();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(requests.Count);
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
{
|
||||
results[i].Path.Should().Be(requests[i].Path);
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
-26
@@ -1,34 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileManagement;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
|
||||
using Mapster;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileManagement;
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PathSegmentMappingConfig"/> class.
|
||||
/// Contains unit tests for the <see cref="PathSegmentMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PathSegmentMappingConfigTests
|
||||
public class PathSegmentMappingTests
|
||||
{
|
||||
private readonly TypeAdapterConfig _config;
|
||||
private readonly PathSegmentMappingConfig _pathSegmentMappingConfig;
|
||||
|
||||
public PathSegmentMappingConfigTests()
|
||||
{
|
||||
_config = new TypeAdapterConfig();
|
||||
_pathSegmentMappingConfig = new PathSegmentMappingConfig();
|
||||
_pathSegmentMappingConfig.Register(_config);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingPathSegmentToPathSegmentResponse_ShouldMapCorrectly()
|
||||
public void ToResponse_WhenMappingPathSegment_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ErrorOr<PathSegment> createResult = PathSegment.Create("TestSegment", true, false);
|
||||
@@ -36,7 +26,7 @@ public class PathSegmentMappingConfigTests
|
||||
PathSegment pathSegment = createResult.Value;
|
||||
|
||||
// Act
|
||||
PathSegmentResponse result = pathSegment.Adapt<PathSegmentResponse>(_config);
|
||||
PathSegmentResponse result = pathSegment.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
@@ -47,7 +37,7 @@ public class PathSegmentMappingConfigTests
|
||||
[InlineData("Folder", true, false)]
|
||||
[InlineData("File.txt", false, false)]
|
||||
[InlineData("C:", false, true)]
|
||||
public void Register_WhenMappingDifferentPathSegmentTypes_ShouldMapCorrectly(string name, bool isDirectory, bool isDrive)
|
||||
public void ToResponse_WhenMappingDifferentPathSegmentTypes_ShouldMapCorrectly(string name, bool isDirectory, bool isDrive)
|
||||
{
|
||||
// Arrange
|
||||
ErrorOr<PathSegment> createResult = PathSegment.Create(name, isDirectory, isDrive);
|
||||
@@ -55,7 +45,7 @@ public class PathSegmentMappingConfigTests
|
||||
PathSegment pathSegment = createResult.Value;
|
||||
|
||||
// Act
|
||||
PathSegmentResponse result = pathSegment.Adapt<PathSegmentResponse>(_config);
|
||||
PathSegmentResponse result = pathSegment.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
@@ -63,7 +53,7 @@ public class PathSegmentMappingConfigTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Register_WhenMappingMultiplePathSegments_ShouldMapAllCorrectly()
|
||||
public void ToResponses_WhenMappingMultiplePathSegments_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<PathSegment> pathSegments =
|
||||
@@ -75,14 +65,13 @@ public class PathSegmentMappingConfigTests
|
||||
];
|
||||
|
||||
// Act
|
||||
List<PathSegmentResponse> results = pathSegments.Adapt<List<PathSegmentResponse>>(_config);
|
||||
IEnumerable<PathSegmentResponse> results = pathSegments.ToResponses();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(pathSegments.Count);
|
||||
List<PathSegmentResponse> resultList = results.ToList();
|
||||
for (int i = 0; i < pathSegments.Count; i++)
|
||||
{
|
||||
results[i].Path.Should().Be(pathSegments[i].Name);
|
||||
}
|
||||
resultList[i].Path.Should().Be(pathSegments[i].Name);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SplitPathRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SplitPathRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SplitPathRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public SplitPathRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingSplitPathRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
SplitPathRequest request = _fixture.Create<SplitPathRequest>();
|
||||
|
||||
// Act
|
||||
SplitPathCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/home/user/documents")]
|
||||
[InlineData("C:\\Users\\Documents")]
|
||||
[InlineData("/var/www/html")]
|
||||
[InlineData("D:\\Projects\\MyProject\\file.txt")]
|
||||
public void ToCommand_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path)
|
||||
{
|
||||
// Arrange
|
||||
SplitPathRequest request = new(path);
|
||||
|
||||
// Act
|
||||
SplitPathCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<SplitPathRequest> requests = _fixture.CreateMany<SplitPathRequest>().ToList();
|
||||
|
||||
// Act
|
||||
List<SplitPathCommand> results = requests.Select(r => r.ToCommand()).ToList();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(requests.Count);
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
results[i].Path.Should().Be(requests[i].Path);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
|
||||
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Path;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ValidatePathRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ValidatePathRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ValidatePathRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public ValidatePathRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingValidatePathRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ValidatePathRequest request = _fixture.Create<ValidatePathRequest>();
|
||||
|
||||
// Act
|
||||
ValidatePathQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/home/user/documents")]
|
||||
[InlineData("C:\\Users\\Documents")]
|
||||
[InlineData("/var/www/html")]
|
||||
[InlineData("D:\\Projects\\MyProject\\file.txt")]
|
||||
[InlineData("\\\\NetworkShare\\Folder")]
|
||||
[InlineData("relative/path/to/file.txt")]
|
||||
public void ToQuery_WhenMappingWithDifferentPaths_ShouldMapCorrectly(string path)
|
||||
{
|
||||
// Arrange
|
||||
ValidatePathRequest request = new(path);
|
||||
|
||||
// Act
|
||||
ValidatePathQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<ValidatePathRequest> requests = _fixture.CreateMany<ValidatePathRequest>().ToList();
|
||||
|
||||
// Act
|
||||
List<ValidatePathQuery> results = requests.Select(r => r.ToQuery()).ToList();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(requests.Count);
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
results[i].Path.Should().Be(requests[i].Path);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails;
|
||||
using Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
|
||||
using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Thumbnails;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetThumbnailRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThumbnailRequestMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetThumbnailRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetThumbnailRequestMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingGetThumbnailRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetThumbnailRequest request = _fixture.Create<GetThumbnailRequest>();
|
||||
|
||||
// Act
|
||||
GetThumbnailQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(request.Path);
|
||||
result.Quality.Should().Be(request.Quality);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("C:\\test\\image.jpg", 50)]
|
||||
[InlineData("/home/user/image.png", 100)]
|
||||
[InlineData("D:\\photos\\vacation\\pic.gif", 75)]
|
||||
public void ToQuery_WhenMappingWithDifferentPathsAndQualities_ShouldMapCorrectly(string path, int quality)
|
||||
{
|
||||
// Arrange
|
||||
GetThumbnailRequest request = new(path, quality);
|
||||
|
||||
// Act
|
||||
GetThumbnailQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Path.Should().Be(path);
|
||||
result.Quality.Should().Be(quality);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<GetThumbnailRequest> requests = _fixture.CreateMany<GetThumbnailRequest>().ToList();
|
||||
|
||||
// Act
|
||||
List<GetThumbnailQuery> results = requests.Select(r => r.ToQuery()).ToList();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(requests.Count);
|
||||
for (int i = 0; i < requests.Count; i++)
|
||||
{
|
||||
results[i].Path.Should().Be(requests[i].Path);
|
||||
results[i].Quality.Should().Be(requests[i].Quality);
|
||||
}
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails;
|
||||
using Lumina.Domain.Common.Enums.PhotoLibrary;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Thumbnails;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThumbnailMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThumbnailMappingTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThumbnailMappingTests"/> class.
|
||||
/// </summary>
|
||||
public ThumbnailMappingTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingThumbnail_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Thumbnail domainModel = _fixture.Create<Thumbnail>();
|
||||
|
||||
// Act
|
||||
ThumbnailResponse result = domainModel.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Type.Should().Be(domainModel.Type);
|
||||
result.Bytes.Should().BeEquivalentTo(domainModel.Bytes);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ImageType.JPEG)]
|
||||
[InlineData(ImageType.PNG)]
|
||||
[InlineData(ImageType.GIF)]
|
||||
public void ToResponse_WhenMappingDifferentImageTypes_ShouldMapCorrectly(ImageType imageType)
|
||||
{
|
||||
// Arrange
|
||||
byte[] bytes = _fixture.CreateMany<byte>(100).ToArray();
|
||||
Thumbnail domainModel = new(imageType, bytes);
|
||||
|
||||
// Act
|
||||
ThumbnailResponse result = domainModel.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Type.Should().Be(imageType);
|
||||
result.Bytes.Should().BeEquivalentTo(bytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingThumbnailWithEmptyBytes_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ImageType imageType = _fixture.Create<ImageType>();
|
||||
byte[] emptyBytes = [];
|
||||
Thumbnail domainModel = new(imageType, emptyBytes);
|
||||
|
||||
// Act
|
||||
ThumbnailResponse result = domainModel.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Type.Should().Be(imageType);
|
||||
result.Bytes.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingMultipleThumbnails_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<Thumbnail> thumbnails = _fixture.CreateMany<Thumbnail>(3).ToList();
|
||||
|
||||
// Act
|
||||
List<ThumbnailResponse> results = thumbnails.Select(t => t.ToResponse()).ToList();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(thumbnails.Count);
|
||||
for (int i = 0; i < thumbnails.Count; i++)
|
||||
{
|
||||
results[i].Type.Should().Be(thumbnails[i].Type);
|
||||
results[i].Bytes.Should().BeEquivalentTo(thumbnails[i].Bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddMediaLibraryRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddMediaLibraryRequestMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = new(
|
||||
Guid.NewGuid(),
|
||||
"My Library",
|
||||
LibraryType.Book,
|
||||
["C:/Books", "D:/Media/Books"]
|
||||
);
|
||||
|
||||
// Act
|
||||
AddLibraryCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.UserId.Should().Be(request.UserId);
|
||||
result.Title.Should().Be(request.Title);
|
||||
result.LibraryType.Should().Be(request.LibraryType);
|
||||
result.ContentLocations.Should().BeEquivalentTo(request.ContentLocations);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryType.Book)]
|
||||
[InlineData(LibraryType.Movie)]
|
||||
[InlineData(LibraryType.TvShow)]
|
||||
[InlineData(LibraryType.Music)]
|
||||
public void ToCommand_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType)
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = new(
|
||||
Guid.NewGuid(),
|
||||
"My Library",
|
||||
libraryType,
|
||||
["C:/Media"]
|
||||
);
|
||||
|
||||
// Act
|
||||
AddLibraryCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.UserId.Should().Be(request.UserId);
|
||||
result.Title.Should().Be(request.Title);
|
||||
result.LibraryType.Should().Be(libraryType);
|
||||
result.ContentLocations.Should().BeEquivalentTo(request.ContentLocations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingMultipleContentLocations_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
string[] contentLocations =
|
||||
[
|
||||
"C:/Media/Books",
|
||||
"D:/Books",
|
||||
"E:/Digital Library/Books",
|
||||
"F:/Reading Material"
|
||||
];
|
||||
|
||||
AddLibraryRequest request = new(
|
||||
Guid.NewGuid(),
|
||||
"My Library",
|
||||
LibraryType.Book,
|
||||
contentLocations
|
||||
);
|
||||
|
||||
// Act
|
||||
AddLibraryCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.ContentLocations.Should().BeEquivalentTo(contentLocations);
|
||||
}
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryEntityMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidLibraryEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "My Library",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations =
|
||||
[
|
||||
new() { Path = "C:/Books" },
|
||||
new() { Path = "D:/Media/Books" }
|
||||
],
|
||||
Created = DateTime.UtcNow,
|
||||
Updated = null
|
||||
};
|
||||
|
||||
// Act
|
||||
LibraryResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Id.Should().Be(entity.Id);
|
||||
result.UserId.Should().Be(entity.UserId);
|
||||
result.Title.Should().Be(entity.Title);
|
||||
result.LibraryType.Should().Be(entity.LibraryType);
|
||||
result.ContentLocations.Should().BeEquivalentTo(entity.ContentLocations.Select(l => l.Path));
|
||||
result.Created.Should().Be(entity.Created);
|
||||
result.Updated.Should().Be(entity.Updated);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryType.Book)]
|
||||
[InlineData(LibraryType.Movie)]
|
||||
[InlineData(LibraryType.TvShow)]
|
||||
[InlineData(LibraryType.Music)]
|
||||
public void ToResponse_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType)
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "My Library",
|
||||
LibraryType = libraryType,
|
||||
ContentLocations = [new() { Path = "C:/Media" }],
|
||||
Created = DateTime.UtcNow,
|
||||
Updated = null
|
||||
};
|
||||
|
||||
// Act
|
||||
LibraryResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.LibraryType.Should().Be(libraryType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingMultipleContentLocations_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "My Library",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations =
|
||||
[
|
||||
new() { Path = "C:/Media/Books" },
|
||||
new() { Path = "D:/Books" },
|
||||
new() { Path = "E:/Digital Library/Books" },
|
||||
new() { Path = "F:/Reading Material" }
|
||||
],
|
||||
Created = DateTime.UtcNow,
|
||||
Updated = null
|
||||
};
|
||||
|
||||
// Act
|
||||
LibraryResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.ContentLocations.Should().BeEquivalentTo(entity.ContentLocations.Select(l => l.Path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingWithUpdatedDateTime_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
DateTime updated = DateTime.UtcNow.AddDays(-1);
|
||||
LibraryEntity entity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "My Library",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations = [new() { Path = "C:/Books" }],
|
||||
Created = DateTime.UtcNow,
|
||||
Updated = updated
|
||||
};
|
||||
|
||||
// Act
|
||||
LibraryResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Updated.Should().Be(updated);
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingValidLibrary_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ErrorOr<Library> libraryResult = Library.Create(
|
||||
Guid.NewGuid(),
|
||||
"Test Library",
|
||||
LibraryType.Book,
|
||||
["C:/Books", "D:/Media/Books"]
|
||||
);
|
||||
Library library = libraryResult.Value;
|
||||
|
||||
// Act
|
||||
LibraryEntity result = library.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Id.Should().Be(library.Id.Value);
|
||||
result.UserId.Should().Be(library.UserId.Value);
|
||||
result.Title.Should().Be(library.Title);
|
||||
result.LibraryType.Should().Be(library.LibraryType);
|
||||
result.ContentLocations.Select(l => l.Path)
|
||||
.Should().BeEquivalentTo(library.ContentLocations.Select(l => l.Path));
|
||||
result.Created.Should().Be(library.Created);
|
||||
result.Updated.Should().Be(library.Updated.HasValue ? library.Updated : null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingLibraryWithEmptyContentLocations_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
ErrorOr<Library> libraryResult = Library.Create(
|
||||
Guid.NewGuid(),
|
||||
"Empty Library",
|
||||
LibraryType.Book,
|
||||
[]
|
||||
);
|
||||
Library library = libraryResult.Value;
|
||||
|
||||
// Act
|
||||
LibraryEntity result = library.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.ContentLocations.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryType.Book)]
|
||||
[InlineData(LibraryType.Movie)]
|
||||
[InlineData(LibraryType.TvShow)]
|
||||
[InlineData(LibraryType.Music)]
|
||||
public void ToRepositoryEntity_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType)
|
||||
{
|
||||
// Arrange
|
||||
ErrorOr<Library> libraryResult = Library.Create(
|
||||
Guid.NewGuid(),
|
||||
"Test Library",
|
||||
libraryType,
|
||||
["C:/Media"]
|
||||
);
|
||||
Library library = libraryResult.Value;
|
||||
|
||||
// Act
|
||||
LibraryEntity result = library.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.LibraryType.Should().Be(libraryType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingMultipleContentLocations_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<string> contentLocations =
|
||||
[
|
||||
"C:/Media/Books",
|
||||
"D:/Books",
|
||||
"E:/Digital Library/Books",
|
||||
"F:/Reading Material"
|
||||
];
|
||||
|
||||
ErrorOr<Library> libraryResult = Library.Create(
|
||||
Guid.NewGuid(),
|
||||
"Test Library",
|
||||
LibraryType.Book,
|
||||
contentLocations
|
||||
);
|
||||
Library library = libraryResult.Value;
|
||||
|
||||
// Act
|
||||
LibraryEntity result = library.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.ContentLocations.Select(l => l.Path)
|
||||
.Should().BeEquivalentTo(library.ContentLocations.Select(l => l.Path));
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Enums.BookLibrary;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddBookRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddBookRequestMappingTests
|
||||
{
|
||||
private readonly AddBookRequestFixture _requestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddBookRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public AddBookRequestMappingTests()
|
||||
{
|
||||
_requestFixture = new AddBookRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest request = _requestFixture.CreateRequestBook();
|
||||
|
||||
// Act
|
||||
AddBookCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Metadata.Should().BeEquivalentTo(request.Metadata);
|
||||
result.Format.Should().Be(request.Format);
|
||||
result.Edition.Should().Be(request.Edition);
|
||||
result.VolumeNumber.Should().Be(request.VolumeNumber);
|
||||
result.Series.Should().BeEquivalentTo(request.Series);
|
||||
result.ASIN.Should().Be(request.ASIN);
|
||||
result.GoodreadsId.Should().Be(request.GoodreadsId);
|
||||
result.LCCN.Should().Be(request.LCCN);
|
||||
result.OCLCNumber.Should().Be(request.OCLCNumber);
|
||||
result.OpenLibraryId.Should().Be(request.OpenLibraryId);
|
||||
result.LibraryThingId.Should().Be(request.LibraryThingId);
|
||||
result.GoogleBooksId.Should().Be(request.GoogleBooksId);
|
||||
result.BarnesAndNobleId.Should().Be(request.BarnesAndNobleId);
|
||||
result.AppleBooksId.Should().Be(request.AppleBooksId);
|
||||
result.ISBNs.Should().BeEquivalentTo(request.ISBNs);
|
||||
result.Contributors.Should().BeEquivalentTo(request.Contributors);
|
||||
result.Ratings.Should().BeEquivalentTo(request.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest request = new(
|
||||
Metadata: new WrittenContentMetadataDto(
|
||||
Title: "Test Book",
|
||||
OriginalTitle: null,
|
||||
Description: null,
|
||||
ReleaseInfo: null,
|
||||
Genres: null,
|
||||
Tags: null,
|
||||
Language: null,
|
||||
OriginalLanguage: null,
|
||||
Publisher: null,
|
||||
PageCount: null),
|
||||
Format: null,
|
||||
Edition: null,
|
||||
VolumeNumber: null,
|
||||
Series: null,
|
||||
ASIN: null,
|
||||
GoodreadsId: null,
|
||||
LCCN: null,
|
||||
OCLCNumber: null,
|
||||
OpenLibraryId: null,
|
||||
LibraryThingId: null,
|
||||
GoogleBooksId: null,
|
||||
BarnesAndNobleId: null,
|
||||
AppleBooksId: null,
|
||||
ISBNs: null,
|
||||
Contributors: null,
|
||||
Ratings: null);
|
||||
|
||||
// Act
|
||||
AddBookCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Metadata.Should().BeEquivalentTo(request.Metadata);
|
||||
result.Format.Should().BeNull();
|
||||
result.Edition.Should().BeNull();
|
||||
result.VolumeNumber.Should().BeNull();
|
||||
result.Series.Should().BeNull();
|
||||
result.ASIN.Should().BeNull();
|
||||
result.GoodreadsId.Should().BeNull();
|
||||
result.LCCN.Should().BeNull();
|
||||
result.OCLCNumber.Should().BeNull();
|
||||
result.OpenLibraryId.Should().BeNull();
|
||||
result.LibraryThingId.Should().BeNull();
|
||||
result.GoogleBooksId.Should().BeNull();
|
||||
result.BarnesAndNobleId.Should().BeNull();
|
||||
result.AppleBooksId.Should().BeNull();
|
||||
result.ISBNs.Should().BeNull();
|
||||
result.Contributors.Should().BeNull();
|
||||
result.Ratings.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest request = new(
|
||||
Metadata: new WrittenContentMetadataDto(
|
||||
Title: "Test Book",
|
||||
OriginalTitle: null,
|
||||
Description: null,
|
||||
ReleaseInfo: null,
|
||||
Genres: null,
|
||||
Tags: null,
|
||||
Language: null,
|
||||
OriginalLanguage: null,
|
||||
Publisher: null,
|
||||
PageCount: null),
|
||||
Format: null,
|
||||
Edition: null,
|
||||
VolumeNumber: null,
|
||||
Series: null,
|
||||
ASIN: null,
|
||||
GoodreadsId: null,
|
||||
LCCN: null,
|
||||
OCLCNumber: null,
|
||||
OpenLibraryId: null,
|
||||
LibraryThingId: null,
|
||||
GoogleBooksId: null,
|
||||
BarnesAndNobleId: null,
|
||||
AppleBooksId: null,
|
||||
ISBNs: [new("978-0-123456-78-9", IsbnFormat.Isbn13)],
|
||||
Contributors:
|
||||
[
|
||||
new(
|
||||
new MediaContributorNameDto("John Doe", "John Smith Doe"),
|
||||
new MediaContributorRoleDto("Author", "Writing")
|
||||
)
|
||||
],
|
||||
Ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)]);
|
||||
|
||||
// Act
|
||||
AddBookCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.ISBNs.Should().BeEquivalentTo(request.ISBNs);
|
||||
result.Contributors.Should().BeEquivalentTo(request.Contributors);
|
||||
result.Ratings.Should().BeEquivalentTo(request.Ratings);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookMappingTests
|
||||
{
|
||||
private readonly BookFixture _bookFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookMappingTests"/> class.
|
||||
/// </summary>
|
||||
public BookMappingTests()
|
||||
{
|
||||
_bookFixture = new BookFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingCompleteBook_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Book book = _bookFixture.CreateDomainBook();
|
||||
|
||||
// Act
|
||||
BookEntity result = book.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Id.Should().Be(book.Id.Value);
|
||||
result.Title.Should().Be(book.Metadata.Title);
|
||||
result.OriginalTitle.Should().Be(book.Metadata.OriginalTitle.HasValue ? book.Metadata.OriginalTitle.Value : null);
|
||||
result.Description.Should().Be(book.Metadata.Description.HasValue ? book.Metadata.Description.Value : null);
|
||||
result.OriginalReleaseDate.Should().Be(book.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? book.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null);
|
||||
result.OriginalReleaseYear.Should().Be(book.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? book.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null);
|
||||
result.ReReleaseDate.Should().Be(book.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? book.Metadata.ReleaseInfo.ReReleaseDate.Value : null);
|
||||
result.ReReleaseYear.Should().Be(book.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? book.Metadata.ReleaseInfo.ReReleaseYear.Value : null);
|
||||
result.ReleaseCountry.Should().Be(book.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? book.Metadata.ReleaseInfo.ReleaseCountry.Value : null);
|
||||
result.ReleaseVersion.Should().Be(book.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? book.Metadata.ReleaseInfo.ReleaseVersion.Value : null);
|
||||
result.LanguageCode.Should().Be(book.Metadata.Language.HasValue ? book.Metadata.Language.Value.LanguageCode : null);
|
||||
result.LanguageName.Should().Be(book.Metadata.Language.HasValue ? book.Metadata.Language.Value.LanguageName : null);
|
||||
result.LanguageNativeName.Should().Be(book.Metadata.Language.HasValue ? book.Metadata.Language.Value.NativeName.Value : null);
|
||||
result.OriginalLanguageCode.Should().Be(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageCode : null);
|
||||
result.OriginalLanguageName.Should().Be(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageName : null);
|
||||
result.OriginalLanguageNativeName.Should().Be(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.NativeName.Value : null);
|
||||
result.Tags.Should().BeEquivalentTo(book.Metadata.Tags.ToRepositoryEntities());
|
||||
result.Genres.Should().BeEquivalentTo(book.Metadata.Genres.ToRepositoryEntities());
|
||||
result.Publisher.Should().Be(book.Metadata.Publisher.HasValue ? book.Metadata.Publisher.Value : null);
|
||||
result.PageCount.Should().Be(book.Metadata.PageCount.HasValue ? book.Metadata.PageCount.Value : null);
|
||||
result.Format.Should().Be(book.Format.HasValue ? book.Format.Value : null);
|
||||
result.Edition.Should().Be(book.Edition.HasValue ? book.Edition.Value : null);
|
||||
result.VolumeNumber.Should().Be(book.VolumeNumber.HasValue ? book.VolumeNumber.Value : null);
|
||||
result.ASIN.Should().Be(book.ASIN.HasValue ? book.ASIN.Value : null);
|
||||
result.GoodreadsId.Should().Be(book.GoodreadsId.HasValue ? book.GoodreadsId.Value : null);
|
||||
result.LCCN.Should().Be(book.LCCN.HasValue ? book.LCCN.Value : null);
|
||||
result.OCLCNumber.Should().Be(book.OCLCNumber.HasValue ? book.OCLCNumber.Value : null);
|
||||
result.OpenLibraryId.Should().Be(book.OpenLibraryId.HasValue ? book.OpenLibraryId.Value : null);
|
||||
result.LibraryThingId.Should().Be(book.LibraryThingId.HasValue ? book.LibraryThingId.Value : null);
|
||||
result.GoogleBooksId.Should().Be(book.GoogleBooksId.HasValue ? book.GoogleBooksId.Value : null);
|
||||
result.BarnesAndNobleId.Should().Be(book.BarnesAndNobleId.HasValue ? book.BarnesAndNobleId.Value : null);
|
||||
result.AppleBooksId.Should().Be(book.AppleBooksId.HasValue ? book.AppleBooksId.Value : null);
|
||||
result.ISBNs.Should().BeEquivalentTo(book.ISBNs.ToRepositoryEntities());
|
||||
result.Ratings.Should().BeEquivalentTo(book.Ratings.ToRepositoryEntities());
|
||||
result.Created.Should().Be(book.Created);
|
||||
result.Updated.Should().Be(book.Updated.HasValue ? book.Updated.Value : null);
|
||||
}
|
||||
}
|
||||
+347
@@ -0,0 +1,347 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook.Fixtures;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookEntityMappingTests
|
||||
{
|
||||
private readonly BookEntityFixture _bookEntityFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookEntityMappingTests"/> class.
|
||||
/// </summary>
|
||||
public BookEntityMappingTests()
|
||||
{
|
||||
_bookEntityFixture = new BookEntityFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidBookEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity bookEntity = _bookEntityFixture.CreateBook();
|
||||
|
||||
// Act
|
||||
ErrorOr<Book> result = bookEntity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Id.Value.Should().Be(bookEntity.Id);
|
||||
result.Value.Metadata.Title.Should().Be(bookEntity.Title);
|
||||
|
||||
if (bookEntity.OriginalTitle is not null)
|
||||
{
|
||||
result.Value.Metadata.OriginalTitle.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.OriginalTitle.Value.Should().Be(bookEntity.OriginalTitle);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.OriginalTitle.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.Description is not null)
|
||||
{
|
||||
result.Value.Metadata.Description.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.Description.Value.Should().Be(bookEntity.Description);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.Description.HasValue.Should().BeFalse();
|
||||
if (bookEntity.OriginalReleaseDate.HasValue)
|
||||
{
|
||||
result.Value.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.ReleaseInfo.OriginalReleaseDate.Value.Should().Be(bookEntity.OriginalReleaseDate.Value);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.OriginalReleaseYear.HasValue)
|
||||
{
|
||||
result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.Value.Should().Be(bookEntity.OriginalReleaseYear.Value);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.ReReleaseDate.HasValue)
|
||||
{
|
||||
result.Value.Metadata.ReleaseInfo.ReReleaseDate.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.ReleaseInfo.ReReleaseDate.Value.Should().Be(bookEntity.ReReleaseDate.Value);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.ReleaseInfo.ReReleaseDate.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.ReReleaseYear.HasValue)
|
||||
{
|
||||
result.Value.Metadata.ReleaseInfo.ReReleaseYear.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.ReleaseInfo.ReReleaseYear.Value.Should().Be(bookEntity.ReReleaseYear.Value);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.ReleaseInfo.ReReleaseYear.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.ReleaseCountry is not null)
|
||||
{
|
||||
result.Value.Metadata.ReleaseInfo.ReleaseCountry.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.ReleaseInfo.ReleaseCountry.Value.Should().Be(bookEntity.ReleaseCountry);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.ReleaseInfo.ReleaseCountry.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.ReleaseVersion is not null)
|
||||
{
|
||||
result.Value.Metadata.ReleaseInfo.ReleaseVersion.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.ReleaseInfo.ReleaseVersion.Value.Should().Be(bookEntity.ReleaseVersion);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.ReleaseInfo.ReleaseVersion.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.LanguageCode is not null)
|
||||
{
|
||||
result.Value.Metadata.Language.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.Language.Value.LanguageCode.Should().Be(bookEntity.LanguageCode);
|
||||
result.Value.Metadata.Language.Value.LanguageName.Should().Be(bookEntity.LanguageName);
|
||||
|
||||
if (bookEntity.LanguageNativeName is not null)
|
||||
{
|
||||
result.Value.Metadata.Language.Value.NativeName.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.Language.Value.NativeName.Value.Should().Be(bookEntity.LanguageNativeName);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.Language.Value.NativeName.HasValue.Should().BeFalse();
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.Language.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.OriginalLanguageCode is not null)
|
||||
{
|
||||
result.Value.Metadata.OriginalLanguage.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.OriginalLanguage.Value.LanguageCode.Should().Be(bookEntity.OriginalLanguageCode);
|
||||
result.Value.Metadata.OriginalLanguage.Value.LanguageName.Should().Be(bookEntity.OriginalLanguageName);
|
||||
|
||||
if (bookEntity.OriginalLanguageNativeName is not null)
|
||||
{
|
||||
result.Value.Metadata.OriginalLanguage.Value.NativeName.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.OriginalLanguage.Value.NativeName.Value.Should().Be(bookEntity.OriginalLanguageNativeName);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.OriginalLanguage.Value.NativeName.HasValue.Should().BeFalse();
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.OriginalLanguage.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.Publisher is not null)
|
||||
{
|
||||
result.Value.Metadata.Publisher.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.Publisher.Value.Should().Be(bookEntity.Publisher);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.Publisher.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.PageCount.HasValue)
|
||||
{
|
||||
result.Value.Metadata.PageCount.HasValue.Should().BeTrue();
|
||||
result.Value.Metadata.PageCount.Value.Should().Be(bookEntity.PageCount.Value);
|
||||
}
|
||||
else
|
||||
result.Value.Metadata.PageCount.HasValue.Should().BeFalse();
|
||||
|
||||
result.Value.Format.Value.Should().Be(bookEntity.Format);
|
||||
|
||||
if (bookEntity.Edition is not null)
|
||||
{
|
||||
result.Value.Edition.HasValue.Should().BeTrue();
|
||||
result.Value.Edition.Value.Should().Be(bookEntity.Edition);
|
||||
}
|
||||
else
|
||||
result.Value.Edition.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.VolumeNumber.HasValue)
|
||||
{
|
||||
result.Value.VolumeNumber.HasValue.Should().BeTrue();
|
||||
result.Value.VolumeNumber.Value.Should().Be(bookEntity.VolumeNumber.Value);
|
||||
}
|
||||
else
|
||||
result.Value.VolumeNumber.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.ASIN is not null)
|
||||
{
|
||||
result.Value.ASIN.HasValue.Should().BeTrue();
|
||||
result.Value.ASIN.Value.Should().Be(bookEntity.ASIN);
|
||||
}
|
||||
else
|
||||
result.Value.ASIN.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.GoodreadsId is not null)
|
||||
{
|
||||
result.Value.GoodreadsId.HasValue.Should().BeTrue();
|
||||
result.Value.GoodreadsId.Value.Should().Be(bookEntity.GoodreadsId);
|
||||
}
|
||||
else
|
||||
result.Value.GoodreadsId.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.LCCN is not null)
|
||||
{
|
||||
result.Value.LCCN.HasValue.Should().BeTrue();
|
||||
result.Value.LCCN.Value.Should().Be(bookEntity.LCCN);
|
||||
}
|
||||
else
|
||||
result.Value.LCCN.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.OCLCNumber is not null)
|
||||
{
|
||||
result.Value.OCLCNumber.HasValue.Should().BeTrue();
|
||||
result.Value.OCLCNumber.Value.Should().Be(bookEntity.OCLCNumber);
|
||||
}
|
||||
else
|
||||
result.Value.OCLCNumber.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.OpenLibraryId is not null)
|
||||
{
|
||||
result.Value.OpenLibraryId.HasValue.Should().BeTrue();
|
||||
result.Value.OpenLibraryId.Value.Should().Be(bookEntity.OpenLibraryId);
|
||||
}
|
||||
else
|
||||
result.Value.OpenLibraryId.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.LibraryThingId is not null)
|
||||
{
|
||||
result.Value.LibraryThingId.HasValue.Should().BeTrue();
|
||||
result.Value.LibraryThingId.Value.Should().Be(bookEntity.LibraryThingId);
|
||||
}
|
||||
else
|
||||
result.Value.LibraryThingId.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.GoogleBooksId is not null)
|
||||
{
|
||||
result.Value.GoogleBooksId.HasValue.Should().BeTrue();
|
||||
result.Value.GoogleBooksId.Value.Should().Be(bookEntity.GoogleBooksId);
|
||||
}
|
||||
else
|
||||
result.Value.GoogleBooksId.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.BarnesAndNobleId is not null)
|
||||
{
|
||||
result.Value.BarnesAndNobleId.HasValue.Should().BeTrue();
|
||||
result.Value.BarnesAndNobleId.Value.Should().Be(bookEntity.BarnesAndNobleId);
|
||||
}
|
||||
else
|
||||
result.Value.BarnesAndNobleId.HasValue.Should().BeFalse();
|
||||
|
||||
if (bookEntity.AppleBooksId is not null)
|
||||
{
|
||||
result.Value.AppleBooksId.HasValue.Should().BeTrue();
|
||||
result.Value.AppleBooksId.Value.Should().Be(bookEntity.AppleBooksId);
|
||||
}
|
||||
else
|
||||
result.Value.AppleBooksId.HasValue.Should().BeFalse();
|
||||
|
||||
result.Value.Created.Should().Be(bookEntity.Created);
|
||||
|
||||
if (bookEntity.Updated.HasValue)
|
||||
{
|
||||
result.Value.Updated.HasValue.Should().BeTrue();
|
||||
result.Value.Updated!.Value.Should().Be(bookEntity.Updated.Value);
|
||||
}
|
||||
else
|
||||
result.Value.Updated.HasValue.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingBookEntity_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity bookEntity = _bookEntityFixture.CreateBook();
|
||||
|
||||
// Act
|
||||
BookResponse result = bookEntity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Id.Should().Be(bookEntity.Id);
|
||||
result.Metadata.Title.Should().Be(bookEntity.Title);
|
||||
result.Metadata.OriginalTitle.Should().Be(bookEntity.OriginalTitle);
|
||||
result.Metadata.Description.Should().Be(bookEntity.Description);
|
||||
result.Metadata.ReleaseInfo!.OriginalReleaseDate.Should().Be(bookEntity.OriginalReleaseDate);
|
||||
result.Metadata.ReleaseInfo.OriginalReleaseYear.Should().Be(bookEntity.OriginalReleaseYear);
|
||||
result.Metadata.ReleaseInfo.ReReleaseDate.Should().Be(bookEntity.ReReleaseDate);
|
||||
result.Metadata.ReleaseInfo.ReReleaseYear.Should().Be(bookEntity.ReReleaseYear);
|
||||
result.Metadata.ReleaseInfo.ReleaseCountry.Should().Be(bookEntity.ReleaseCountry);
|
||||
result.Metadata.ReleaseInfo.ReleaseVersion.Should().Be(bookEntity.ReleaseVersion);
|
||||
result.Metadata.Language.Should().NotBeNull();
|
||||
result.Metadata.Language!.LanguageCode.Should().Be(bookEntity.LanguageCode);
|
||||
result.Metadata.Language.LanguageName.Should().Be(bookEntity.LanguageName);
|
||||
result.Metadata.Language.NativeName.Should().Be(bookEntity.LanguageNativeName);
|
||||
result.Metadata.OriginalLanguage.Should().NotBeNull();
|
||||
result.Metadata.OriginalLanguage!.LanguageCode.Should().Be(bookEntity.OriginalLanguageCode);
|
||||
result.Metadata.OriginalLanguage.LanguageName.Should().Be(bookEntity.OriginalLanguageName);
|
||||
result.Metadata.OriginalLanguage.NativeName.Should().Be(bookEntity.OriginalLanguageNativeName);
|
||||
result.Metadata.Publisher.Should().Be(bookEntity.Publisher);
|
||||
result.Metadata.PageCount.Should().Be(bookEntity.PageCount);
|
||||
result.Format.Should().Be(bookEntity.Format);
|
||||
result.Edition.Should().Be(bookEntity.Edition);
|
||||
result.VolumeNumber.Should().Be(bookEntity.VolumeNumber);
|
||||
result.ASIN.Should().Be(bookEntity.ASIN);
|
||||
result.GoodreadsId.Should().Be(bookEntity.GoodreadsId);
|
||||
result.LCCN.Should().Be(bookEntity.LCCN);
|
||||
result.OCLCNumber.Should().Be(bookEntity.OCLCNumber);
|
||||
result.OpenLibraryId.Should().Be(bookEntity.OpenLibraryId);
|
||||
result.LibraryThingId.Should().Be(bookEntity.LibraryThingId);
|
||||
result.GoogleBooksId.Should().Be(bookEntity.GoogleBooksId);
|
||||
result.BarnesAndNobleId.Should().Be(bookEntity.BarnesAndNobleId);
|
||||
result.AppleBooksId.Should().Be(bookEntity.AppleBooksId);
|
||||
result.ISBNs.Should().BeEquivalentTo(bookEntity.ISBNs);
|
||||
result.Ratings.Should().BeEquivalentTo(bookEntity.Ratings);
|
||||
result.Created.Should().Be(bookEntity.Created);
|
||||
result.Updated.Should().Be(bookEntity.Updated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainModels_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> bookEntities =
|
||||
[
|
||||
_bookEntityFixture.CreateBook(),
|
||||
_bookEntityFixture.CreateBook()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<Book>> results = bookEntities.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(bookEntities.Count);
|
||||
results.Should().AllSatisfy(result => result.IsError.Should().BeFalse());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> bookEntities =
|
||||
[
|
||||
_bookEntityFixture.CreateBook(),
|
||||
_bookEntityFixture.CreateBook()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<BookResponse> results = bookEntities.ToResponses();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(bookEntities.Count);
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookRatingDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookRatingDtoMappingTests
|
||||
{
|
||||
private readonly BookRatingDtoFixture _bookRatingDtoFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookRatingDtoMappingTests"/> class.
|
||||
/// </summary>
|
||||
public BookRatingDtoMappingTests()
|
||||
{
|
||||
_bookRatingDtoFixture = new BookRatingDtoFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingCompleteBookRatinDto_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
BookRatingDto dto = _bookRatingDtoFixture.CreateComplete();
|
||||
|
||||
// Act
|
||||
ErrorOr<BookRating> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Value.Should().Be(dto.Value!.Value);
|
||||
result.Value.MaxValue.Should().Be(dto.MaxValue!.Value);
|
||||
|
||||
if (dto.Source.HasValue)
|
||||
{
|
||||
result.Value.Source.HasValue.Should().BeTrue();
|
||||
result.Value.Source.Value.Should().Be(dto.Source.Value);
|
||||
}
|
||||
else
|
||||
result.Value.Source.HasValue.Should().BeFalse();
|
||||
|
||||
if (dto.VoteCount.HasValue)
|
||||
{
|
||||
result.Value.VoteCount.HasValue.Should().BeTrue();
|
||||
result.Value.VoteCount.Value.Should().Be(dto.VoteCount.Value);
|
||||
}
|
||||
else
|
||||
result.Value.VoteCount.HasValue.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingMinimalBookRatingDto_ShouldMapRequiredPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
BookRatingDto dto = _bookRatingDtoFixture.CreateMinimal();
|
||||
|
||||
// Act
|
||||
ErrorOr<BookRating> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Value.Should().Be(dto.Value!.Value);
|
||||
result.Value.MaxValue.Should().Be(dto.MaxValue!.Value);
|
||||
result.Value.Source.HasValue.Should().BeFalse();
|
||||
result.Value.VoteCount.HasValue.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingInvalidBookRatingDto_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
BookRatingDto dto = _bookRatingDtoFixture.CreateInvalid();
|
||||
|
||||
// Act
|
||||
ErrorOr<BookRating> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainModels_WhenMappingMultipleValidBookRatingDtos_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<BookRatingDto> dtos =
|
||||
[
|
||||
_bookRatingDtoFixture.CreateComplete(),
|
||||
_bookRatingDtoFixture.CreateMinimal()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<BookRating>> results = dtos.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(dtos.Count);
|
||||
|
||||
List<ErrorOr<BookRating>> resultList = results.ToList();
|
||||
resultList.Should().AllSatisfy(result => result.IsError.Should().BeFalse());
|
||||
|
||||
// Complete rating
|
||||
resultList[0].Value.Value.Should().Be(dtos[0].Value!.Value);
|
||||
resultList[0].Value.MaxValue.Should().Be(dtos[0].MaxValue!.Value);
|
||||
resultList[0].Value.Source.Value.Should().Be(dtos[0].Source!.Value);
|
||||
resultList[0].Value.VoteCount.Value.Should().Be(dtos[0].VoteCount!.Value);
|
||||
|
||||
// Minimal rating
|
||||
resultList[1].Value.Value.Should().Be(dtos[1].Value!.Value);
|
||||
resultList[1].Value.MaxValue.Should().Be(dtos[1].MaxValue!.Value);
|
||||
resultList[1].Value.Source.HasValue.Should().BeFalse();
|
||||
resultList[1].Value.VoteCount.HasValue.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainModels_WhenMappingMixedValidAndInvalidBookRatingDtos_ShouldReturnMixedResults()
|
||||
{
|
||||
// Arrange
|
||||
List<BookRatingDto> dtos =
|
||||
[
|
||||
_bookRatingDtoFixture.CreateComplete(),
|
||||
_bookRatingDtoFixture.CreateInvalid(),
|
||||
_bookRatingDtoFixture.CreateMinimal()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<BookRating>> results = dtos.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(dtos.Count);
|
||||
|
||||
List<ErrorOr<BookRating>> resultList = results.ToList();
|
||||
|
||||
resultList[0].IsError.Should().BeFalse();
|
||||
resultList[1].IsError.Should().BeTrue();
|
||||
resultList[2].IsError.Should().BeFalse();
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookRatingEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookRatingEntityMappingTests
|
||||
{
|
||||
private readonly BookRatingEntityFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookRatingEntityMappingTests"/> class.
|
||||
/// </summary>
|
||||
public BookRatingEntityMappingTests()
|
||||
{
|
||||
_fixture = new BookRatingEntityFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidBookRatingEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
BookRatingEntity entity = _fixture.CreateBookRating();
|
||||
|
||||
// Act
|
||||
BookRatingDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Value.Should().Be(entity.Value!.Value);
|
||||
result.MaxValue.Should().Be(entity.MaxValue!.Value);
|
||||
result.Source.Should().Be(entity.Source);
|
||||
result.VoteCount.Should().Be(entity.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults()
|
||||
{
|
||||
// Arrange
|
||||
BookRatingEntity entity = _fixture.CreateInvalidBookRating();
|
||||
|
||||
// Act
|
||||
BookRatingDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Value.Should().Be(default);
|
||||
result.MaxValue.Should().Be(default);
|
||||
result.Source.Should().Be(entity.Source);
|
||||
result.VoteCount.Should().Be(entity.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<BookRatingEntity> entities =
|
||||
[
|
||||
_fixture.CreateBookRating(),
|
||||
_fixture.CreateBookRating()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<BookRatingDto> results = entities.ToResponses();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(entities.Count);
|
||||
results.Should().AllSatisfy(result =>
|
||||
{
|
||||
result.Should().NotBeNull();
|
||||
result.Value.Should().BeInRange(1, 5);
|
||||
result.MaxValue.Should().Be(5);
|
||||
result.VoteCount.Should().BeInRange(1, 1000);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidBookRatingEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
BookRatingEntity entity = _fixture.CreateBookRating();
|
||||
|
||||
// Act
|
||||
ErrorOr<BookRating> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Value.Should().Be(entity.Value);
|
||||
result.Value.MaxValue.Should().Be(entity.MaxValue);
|
||||
result.Value.Source.Value.Should().Be(entity.Source);
|
||||
result.Value.VoteCount.Value.Should().Be(entity.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingInvalidBookRatingEntity_ShouldMapToDefaults()
|
||||
{
|
||||
// Arrange
|
||||
BookRatingEntity entity = _fixture.CreateInvalidBookRating();
|
||||
|
||||
// Act
|
||||
ErrorOr<BookRating> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Value.Should().Be(default);
|
||||
result.Value.MaxValue.Should().Be(default);
|
||||
result.Value.Source.HasValue.Should().BeFalse();
|
||||
result.Value.VoteCount.HasValue.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleBookRatingEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<BookRatingEntity> entities =
|
||||
[
|
||||
_fixture.CreateBookRating(),
|
||||
_fixture.CreateBookRating()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<BookRating>> results = entities.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(entities.Count);
|
||||
results.Should().AllSatisfy(result =>
|
||||
{
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Value.Should().BeInRange(1, 5);
|
||||
result.Value.MaxValue.Should().Be(5);
|
||||
result.Value.Source.HasValue.Should().BeTrue();
|
||||
result.Value.VoteCount.Value.Should().BeInRange(1, 1000);
|
||||
});
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookRatingMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookRatingMappingTests
|
||||
{
|
||||
private readonly BookRatingFixture _bookRatingFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookRatingMappingTests"/> class.
|
||||
/// </summary>
|
||||
public BookRatingMappingTests()
|
||||
{
|
||||
_bookRatingFixture = new BookRatingFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingCompleteBookRating_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
BookRating bookRating = _bookRatingFixture.CreateBookRating();
|
||||
|
||||
// Act
|
||||
BookRatingEntity result = bookRating.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Value.Should().Be(bookRating.Value);
|
||||
result.MaxValue.Should().Be(bookRating.MaxValue);
|
||||
result.Source.Should().Be(bookRating.Source.Value);
|
||||
result.VoteCount.Should().Be(bookRating.VoteCount.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingBookRatingWithoutSource_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
BookRating bookRating = _bookRatingFixture.CreateBookRatingWithoutSource();
|
||||
|
||||
// Act
|
||||
BookRatingEntity result = bookRating.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Value.Should().Be(bookRating.Value);
|
||||
result.MaxValue.Should().Be(bookRating.MaxValue);
|
||||
result.Source.Should().BeNull();
|
||||
result.VoteCount.Should().Be(bookRating.VoteCount.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingBookRatingWithoutVoteCount_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
BookRating bookRating = _bookRatingFixture.CreateBookRatingWithoutVoteCount();
|
||||
|
||||
// Act
|
||||
BookRatingEntity result = bookRating.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Value.Should().Be(bookRating.Value);
|
||||
result.MaxValue.Should().Be(bookRating.MaxValue);
|
||||
result.Source.Should().Be(bookRating.Source.Value);
|
||||
result.VoteCount.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntities_WhenMappingMultipleBookRatings_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<BookRating> bookRatings =
|
||||
[
|
||||
_bookRatingFixture.CreateBookRating(),
|
||||
_bookRatingFixture.CreateBookRatingWithoutSource(),
|
||||
_bookRatingFixture.CreateBookRatingWithoutVoteCount()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<BookRatingEntity> results = bookRatings.ToRepositoryEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(bookRatings.Count);
|
||||
|
||||
List<BookRatingEntity> resultList = results.ToList();
|
||||
|
||||
// Complete rating
|
||||
resultList[0].Value.Should().Be(bookRatings[0].Value);
|
||||
resultList[0].MaxValue.Should().Be(bookRatings[0].MaxValue);
|
||||
resultList[0].Source.Should().Be(bookRatings[0].Source.Value);
|
||||
resultList[0].VoteCount.Should().Be(bookRatings[0].VoteCount.Value);
|
||||
|
||||
// Rating without source
|
||||
resultList[1].Value.Should().Be(bookRatings[1].Value);
|
||||
resultList[1].MaxValue.Should().Be(bookRatings[1].MaxValue);
|
||||
resultList[1].Source.Should().BeNull();
|
||||
resultList[1].VoteCount.Should().Be(bookRatings[1].VoteCount.Value);
|
||||
|
||||
// Rating without vote count
|
||||
resultList[2].Value.Should().Be(bookRatings[2].Value);
|
||||
resultList[2].MaxValue.Should().Be(bookRatings[2].MaxValue);
|
||||
resultList[2].Source.Should().Be(bookRatings[2].Source.Value);
|
||||
resultList[2].VoteCount.Should().BeNull();
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="IsbnDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsbnDtoMappingTests
|
||||
{
|
||||
private readonly IsbnDtoFixture _isbnDtoFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="IsbnDtoMappingTests"/> class.
|
||||
/// </summary>
|
||||
public IsbnDtoMappingTests()
|
||||
{
|
||||
_isbnDtoFixture = new IsbnDtoFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidIsbn10Dto_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IsbnDto dto = _isbnDtoFixture.CreateIsbn10();
|
||||
|
||||
// Act
|
||||
ErrorOr<Isbn> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Value.Should().Be(dto.Value);
|
||||
result.Value.Format.Should().Be(dto.Format!.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidIsbn13Dto_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IsbnDto dto = _isbnDtoFixture.CreateIsbn13();
|
||||
|
||||
// Act
|
||||
ErrorOr<Isbn> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Value.Should().Be(dto.Value);
|
||||
result.Value.Format.Should().Be(dto.Format!.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingDtoWithoutFormat_ShouldUseDefaultFormat()
|
||||
{
|
||||
// Arrange
|
||||
IsbnDto dto = _isbnDtoFixture.CreateWithoutFormat();
|
||||
|
||||
// Act
|
||||
ErrorOr<Isbn> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Value.Should().Be(dto.Value);
|
||||
result.Value.Format.Should().Be(IsbnFormat.Isbn13); // Default format
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingInvalidIsbnDto_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
IsbnDto dto = _isbnDtoFixture.CreateInvalid();
|
||||
|
||||
// Act
|
||||
ErrorOr<Isbn> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainModels_WhenMappingMultipleValidIsbnDtos_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<IsbnDto> dtos =
|
||||
[
|
||||
_isbnDtoFixture.CreateIsbn10(),
|
||||
_isbnDtoFixture.CreateIsbn13(),
|
||||
_isbnDtoFixture.CreateWithoutFormat()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<Isbn>> results = dtos.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(dtos.Count);
|
||||
|
||||
List<ErrorOr<Isbn>> resultList = results.ToList();
|
||||
resultList.Should().AllSatisfy(result => result.IsError.Should().BeFalse());
|
||||
|
||||
resultList[0].Value.Value.Should().Be(dtos[0].Value);
|
||||
resultList[0].Value.Format.Should().Be(dtos[0].Format!.Value);
|
||||
|
||||
resultList[1].Value.Value.Should().Be(dtos[1].Value);
|
||||
resultList[1].Value.Format.Should().Be(dtos[1].Format!.Value);
|
||||
|
||||
resultList[2].Value.Value.Should().Be(dtos[2].Value);
|
||||
resultList[2].Value.Format.Should().Be(IsbnFormat.Isbn13); // Default format
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainModels_WhenMappingMixedValidAndInvalidIsbnDtos_ShouldReturnMixedResults()
|
||||
{
|
||||
// Arrange
|
||||
List<IsbnDto> dtos =
|
||||
[
|
||||
_isbnDtoFixture.CreateIsbn10(),
|
||||
_isbnDtoFixture.CreateInvalid(),
|
||||
_isbnDtoFixture.CreateIsbn13()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<Isbn>> results = dtos.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(dtos.Count);
|
||||
|
||||
List<ErrorOr<Isbn>> resultList = results.ToList();
|
||||
|
||||
resultList[0].IsError.Should().BeFalse();
|
||||
resultList[0].Value.Value.Should().Be(dtos[0].Value);
|
||||
|
||||
resultList[1].IsError.Should().BeTrue();
|
||||
|
||||
resultList[2].IsError.Should().BeFalse();
|
||||
resultList[2].Value.Value.Should().Be(dtos[2].Value);
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="IsbnEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsbnEntityMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidIsbnEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity entity = new("0-7475-3269-9", IsbnFormat.Isbn10);
|
||||
|
||||
// Act
|
||||
IsbnDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Value.Should().Be(entity.Value);
|
||||
result.Format.Should().Be(entity.Format);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("0-7475-3269-9", IsbnFormat.Isbn10)]
|
||||
[InlineData("978-0-7475-3269-9", IsbnFormat.Isbn13)]
|
||||
public void ToResponse_WhenMappingDifferentValidIsbnEntities_ShouldMapCorrectly(string value, IsbnFormat format)
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity entity = new(value, format);
|
||||
|
||||
// Act
|
||||
IsbnDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Value.Should().Be(value);
|
||||
result.Format.Should().Be(format);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("", null)]
|
||||
[InlineData(" ", null)]
|
||||
[InlineData(null, null)]
|
||||
public void ToResponse_WhenMappingInvalidIsbnEntity_ShouldPreserveValues(string? value, IsbnFormat? format)
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity entity = new(value, format);
|
||||
|
||||
// Act
|
||||
IsbnDto result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Value.Should().Be(value);
|
||||
result.Format.Should().Be(format);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingValidIsbnEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity entity = new("0-7475-3269-9", IsbnFormat.Isbn10);
|
||||
|
||||
// Act
|
||||
ErrorOr<Isbn> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Value.Should().Be(entity.Value);
|
||||
result.Value.Format.Should().Be(entity.Format);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData(null)]
|
||||
public void ToDomainEntity_WhenMappingInvalidIsbnEntity_ShouldReturnError(string? invalidValue)
|
||||
{
|
||||
// Arrange
|
||||
IsbnEntity entity = new(invalidValue, null);
|
||||
|
||||
// Act
|
||||
ErrorOr<Isbn> result = entity.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntities_WhenMappingMultipleValidIsbnEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<IsbnEntity> entities =
|
||||
[
|
||||
new IsbnEntity("0-7475-3269-9", IsbnFormat.Isbn10),
|
||||
new IsbnEntity("978-0-7475-3269-9", IsbnFormat.Isbn13)
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<ErrorOr<Isbn>> results = entities.ToDomainEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(entities.Count);
|
||||
|
||||
List<ErrorOr<Isbn>> resultList = results.ToList();
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
resultList[i].IsError.Should().BeFalse();
|
||||
resultList[i].Value.Value.Should().Be(entities[i].Value);
|
||||
resultList[i].Value.Format.Should().Be(entities[i].Format);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleValidIsbnEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<IsbnEntity> entities =
|
||||
[
|
||||
new IsbnEntity("0-7475-3269-9", IsbnFormat.Isbn10),
|
||||
new IsbnEntity("978-0-7475-3269-9", IsbnFormat.Isbn13)
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<IsbnDto> results = entities.ToResponses();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(entities.Count);
|
||||
|
||||
List<IsbnDto> resultList = results.ToList();
|
||||
for (int i = 0; i < entities.Count; i++)
|
||||
{
|
||||
resultList[i].Value.Should().Be(entities[i].Value);
|
||||
resultList[i].Format.Should().Be(entities[i].Format);
|
||||
}
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Common.Fixtures;
|
||||
using Lumina.Domain.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="IsbnMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IsbnMappingTests
|
||||
{
|
||||
private readonly IsbnFixture _isbnFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="IsbnMappingTests"/> class.
|
||||
/// </summary>
|
||||
public IsbnMappingTests()
|
||||
{
|
||||
_isbnFixture = new IsbnFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingIsbn10_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Isbn isbn = _isbnFixture.CreateIsbn10();
|
||||
|
||||
// Act
|
||||
IsbnEntity result = isbn.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Value.Should().Be(isbn.Value);
|
||||
result.Format.Should().Be(IsbnFormat.Isbn10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingIsbn13_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Isbn isbn = _isbnFixture.CreateIsbn13();
|
||||
|
||||
// Act
|
||||
IsbnEntity result = isbn.ToRepositoryEntity();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Value.Should().Be(isbn.Value);
|
||||
result.Format.Should().Be(IsbnFormat.Isbn13);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntities_WhenMappingMultipleIsbns_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<Isbn> isbns =
|
||||
[
|
||||
_isbnFixture.CreateIsbn10(),
|
||||
_isbnFixture.CreateIsbn13(),
|
||||
_isbnFixture.CreateIsbn10()
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<IsbnEntity> results = isbns.ToRepositoryEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().HaveCount(isbns.Count);
|
||||
|
||||
List<IsbnEntity> resultList = results.ToList();
|
||||
for (int i = 0; i < isbns.Count; i++)
|
||||
{
|
||||
resultList[i].Value.Should().Be(isbns[i].Value);
|
||||
resultList[i].Format.Should().Be(isbns[i].Format);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntities_WhenMappingEmptyCollection_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
List<Isbn> isbns = [];
|
||||
|
||||
// Act
|
||||
IEnumerable<IsbnEntity> results = isbns.ToRepositoryEntities();
|
||||
|
||||
// Assert
|
||||
results.Should().NotBeNull();
|
||||
results.Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UserEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserEntityFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid user entity.
|
||||
/// </summary>
|
||||
/// <param name="libraryCount">Number of libraries to generate. Default is 0.</param>
|
||||
/// <returns>The created user entity.</returns>
|
||||
public static UserEntity CreateUserEntity(int libraryCount = 0)
|
||||
{
|
||||
Guid userId = Guid.NewGuid();
|
||||
List<LibraryEntity> libraries = [.. new Faker<LibraryEntity>()
|
||||
.CustomInstantiator(f => new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = f.Commerce.ProductName(),
|
||||
LibraryType = f.PickRandom<LibraryType>(),
|
||||
ContentLocations = [],
|
||||
Created = f.Date.Past(),
|
||||
Updated = null
|
||||
})
|
||||
.Generate(libraryCount)];
|
||||
|
||||
return new Faker<UserEntity>()
|
||||
.CustomInstantiator(f => new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = default!,
|
||||
Password = default!,
|
||||
Created = default,
|
||||
TotpSecret = default,
|
||||
Libraries = libraries
|
||||
})
|
||||
.RuleFor(x => x.Username, f => f.Internet.UserName())
|
||||
.RuleFor(x => x.Password, f => Uri.EscapeDataString(f.Internet.Password()))
|
||||
.RuleFor(x => x.Created, f => f.Date.Past())
|
||||
.RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32) : null)
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of user entities.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of entities to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public static List<UserEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return Enumerable.Range(0, count)
|
||||
.Select(_ => CreateUserEntity())
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Application.Common.Mapping.UsersManagement.Users;
|
||||
using Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users.Fixtures;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Users;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserEntityMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserEntityMappingTests
|
||||
{
|
||||
private readonly UserEntityFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserEntityMappingTests"/> class.
|
||||
/// </summary>
|
||||
public UserEntityMappingTests()
|
||||
{
|
||||
_fixture = new UserEntityFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingValidUserEntity_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity entity = UserEntityFixture.CreateUserEntity();
|
||||
|
||||
// Act
|
||||
UserResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Id.Should().Be(entity.Id);
|
||||
result.Username.Should().Be(entity.Username);
|
||||
result.Created.Should().Be(entity.Created);
|
||||
result.Updated.Should().Be(entity.Updated);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("user1")]
|
||||
[InlineData("test.user")]
|
||||
[InlineData("john_doe")]
|
||||
[InlineData("jane.doe@example.com")]
|
||||
public void ToResponse_WhenMappingDifferentUsernames_ShouldMapCorrectly(string username)
|
||||
{
|
||||
// Arrange
|
||||
UserEntity entity = UserEntityFixture.CreateUserEntity();
|
||||
entity.Username = username;
|
||||
|
||||
// Act
|
||||
UserResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingWithUpdatedDateTime_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity entity = UserEntityFixture.CreateUserEntity();
|
||||
entity.Updated = DateTime.UtcNow.AddDays(-1);
|
||||
|
||||
// Act
|
||||
UserResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Updated.Should().Be(entity.Updated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingWithLibraries_ShouldNotAffectMapping()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity entity = UserEntityFixture.CreateUserEntity(2);
|
||||
|
||||
// Act
|
||||
UserResponse result = entity.ToResponse();
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Id.Should().Be(entity.Id);
|
||||
result.Username.Should().Be(entity.Username);
|
||||
result.Created.Should().Be(entity.Created);
|
||||
result.Updated.Should().Be(entity.Updated);
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Mapping.Common.Metadata;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
|
||||
using Lumina.Application.Common.Mapping.UsersManagement.Users;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UserMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UserMappingTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenMappingValidUser_ShouldOnlyUpdateUsername()
|
||||
{
|
||||
// Arrange
|
||||
User domainEntity = User.Create(
|
||||
UserId.Create(Guid.NewGuid()),
|
||||
"newusername"
|
||||
).Value;
|
||||
|
||||
UserEntity repositoryEntity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "oldusername",
|
||||
Password = "hashedpassword",
|
||||
TotpSecret = "totpsecret",
|
||||
VerificationToken = "verificationtoken",
|
||||
VerificationTokenCreated = DateTime.UtcNow,
|
||||
Libraries = [],
|
||||
Created = DateTime.UtcNow,
|
||||
Updated = null
|
||||
};
|
||||
|
||||
// Act
|
||||
UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Should().BeSameAs(repositoryEntity); // Should modify the same instance
|
||||
result.Username.Should().Be(domainEntity.Username); // Only username should be updated
|
||||
|
||||
// Verify other properties remain unchanged
|
||||
result.Id.Should().Be(repositoryEntity.Id);
|
||||
result.Password.Should().Be(repositoryEntity.Password);
|
||||
result.TotpSecret.Should().Be(repositoryEntity.TotpSecret);
|
||||
result.VerificationToken.Should().Be(repositoryEntity.VerificationToken);
|
||||
result.VerificationTokenCreated.Should().Be(repositoryEntity.VerificationTokenCreated);
|
||||
result.Libraries.Should().BeSameAs(repositoryEntity.Libraries);
|
||||
result.Created.Should().Be(repositoryEntity.Created);
|
||||
result.Updated.Should().Be(repositoryEntity.Updated);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("user1")]
|
||||
[InlineData("test.user")]
|
||||
[InlineData("john_doe")]
|
||||
[InlineData("jane.doe@example.com")]
|
||||
public void ToRepositoryEntity_WhenMappingDifferentUsernames_ShouldUpdateCorrectly(string newUsername)
|
||||
{
|
||||
// Arrange
|
||||
User domainEntity = User.Create(
|
||||
UserId.Create(Guid.NewGuid()),
|
||||
newUsername
|
||||
).Value;
|
||||
|
||||
UserEntity repositoryEntity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "oldusername",
|
||||
Password = "hashedpassword",
|
||||
Libraries = [],
|
||||
Created = DateTime.UtcNow,
|
||||
Updated = null
|
||||
};
|
||||
|
||||
// Act
|
||||
UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Username.Should().Be(newUsername);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenRepositoryEntityHasLibraries_ShouldPreserveLibraries()
|
||||
{
|
||||
// Arrange
|
||||
User domainEntity = User.Create(
|
||||
UserId.Create(Guid.NewGuid()),
|
||||
"newusername"
|
||||
).Value;
|
||||
|
||||
List<LibraryEntity> libraries =
|
||||
[
|
||||
new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "Library 1",
|
||||
LibraryType = LibraryType.Book,
|
||||
ContentLocations = [],
|
||||
Created = DateTime.UtcNow,
|
||||
Updated = null
|
||||
},
|
||||
new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Title = "Library 2",
|
||||
LibraryType = LibraryType.Movie,
|
||||
ContentLocations = [],
|
||||
Created = DateTime.UtcNow,
|
||||
Updated = null
|
||||
}
|
||||
];
|
||||
|
||||
UserEntity repositoryEntity = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = "oldusername",
|
||||
Password = "hashedpassword",
|
||||
Libraries = libraries,
|
||||
Created = DateTime.UtcNow,
|
||||
Updated = null
|
||||
};
|
||||
|
||||
// Act
|
||||
UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Libraries.Should().BeSameAs(libraries);
|
||||
result.Libraries.Should().HaveCount(2);
|
||||
}
|
||||
}
|
||||
-168
@@ -1,168 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree;
|
||||
using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories;
|
||||
using Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetDirectoryTree.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.FileManagement.Files.Fixtures;
|
||||
using Lumina.Application.UnitTests.Core.FileManagement.Pahs.Fixtures;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.ValueObjects;
|
||||
using MapsterMapper;
|
||||
using NSubstitute;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Queries.GetTreeDirectories;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTreeDirectoriesQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTreeDirectoriesQueryHandlerTests
|
||||
{
|
||||
private readonly IFixture _fixture;
|
||||
private readonly IMapper _mockMapper;
|
||||
private readonly IDirectoryService _mockDirectoryService;
|
||||
private readonly GetTreeDirectoriesQueryHandler _sut;
|
||||
private readonly GetTreeDirectoriesQueryFixture _getTreeDirectoriesQueryFixture;
|
||||
private readonly DirectoryFixture _directoryFixture;
|
||||
private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTreeDirectoriesQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetTreeDirectoriesQueryHandlerTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_mockDirectoryService = Substitute.For<IDirectoryService>();
|
||||
_mockMapper = Substitute.For<IMapper>();
|
||||
_sut = new GetTreeDirectoriesQueryHandler(_mockDirectoryService, _mockMapper);
|
||||
_getTreeDirectoriesQueryFixture = new GetTreeDirectoriesQueryFixture();
|
||||
_directoryFixture = new DirectoryFixture();
|
||||
_fileSystemTreeNodeResponseFixture = new FileSystemTreeNodeResponseFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(false);
|
||||
|
||||
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
|
||||
IEnumerable<FileSystemTreeNodeResponse> directoryResponses = _fileSystemTreeNodeResponseFixture.CreateMany(directories.Count());
|
||||
|
||||
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements)
|
||||
.Returns(ErrorOrFactory.From(directories));
|
||||
|
||||
_mockMapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories))
|
||||
.Returns(directoryResponses);
|
||||
|
||||
// Act
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
|
||||
result.Value.Should().BeEquivalentTo(directoryResponses);
|
||||
_mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements);
|
||||
_mockMapper.Received(1).Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesQuery getDirectoriesQuery = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true);
|
||||
|
||||
IEnumerable<Directory> directories = _directoryFixture.CreateMany();
|
||||
IEnumerable<FileSystemTreeNodeResponse> directoryResponses = _fileSystemTreeNodeResponseFixture.CreateMany(directories.Count());
|
||||
|
||||
_mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements)
|
||||
.Returns(ErrorOrFactory.From(directories));
|
||||
|
||||
_mockMapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories))
|
||||
.Returns(directoryResponses);
|
||||
|
||||
// Act
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(getDirectoriesQuery, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
|
||||
result.Value.Should().BeEquivalentTo(directoryResponses);
|
||||
_mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path, getDirectoriesQuery.IncludeHiddenElements);
|
||||
_mockMapper.Received(1).Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == directories));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenDirectoryServiceReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesQuery query = _fixture.Create<GetTreeDirectoriesQuery>();
|
||||
Error error = Error.Failure("DirectoryService.Error", "An error occurred");
|
||||
_mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements)
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.FirstError.Should().Be(error);
|
||||
_mockDirectoryService.Received(1).GetSubdirectories(query.Path, query.IncludeHiddenElements);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenDirectoryServiceReturnsEmptyList_ShouldReturnEmptySuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesQuery query = _fixture.Create<GetTreeDirectoriesQuery>();
|
||||
ErrorOr<IEnumerable<Directory>> emptyList = ErrorOrFactory.From(Enumerable.Empty<Directory>());
|
||||
_mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements)
|
||||
.Returns(emptyList);
|
||||
|
||||
// Act
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().BeEmpty();
|
||||
_mockDirectoryService.Received(1).GetSubdirectories(query.Path, query.IncludeHiddenElements);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenCalledWithNestedDirectories_ShouldReturnCorrectlyNestedResponse()
|
||||
{
|
||||
// Arrange
|
||||
GetTreeDirectoriesQuery query = GetTreeDirectoriesQueryFixture.CreateGetTreeDirectoryQuery(true);
|
||||
IEnumerable<Directory> nestedDirectories = _directoryFixture.CreateManyNested();
|
||||
IEnumerable<FileSystemTreeNodeResponse> nestedResponses = _fileSystemTreeNodeResponseFixture.CreateMany(2, 2, 2);
|
||||
|
||||
_mockDirectoryService.GetSubdirectories(query.Path, query.IncludeHiddenElements)
|
||||
.Returns(ErrorOrFactory.From(nestedDirectories));
|
||||
|
||||
_mockMapper.Map<IEnumerable<FileSystemTreeNodeResponse>>(Arg.Is<IEnumerable<Directory>>(d => d == nestedDirectories))
|
||||
.Returns(nestedResponses);
|
||||
|
||||
// Act
|
||||
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sut.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().BeAssignableTo<IEnumerable<FileSystemTreeNodeResponse>>();
|
||||
result.Value.Should().BeEquivalentTo(nestedResponses, options => options.IncludingNestedObjects());
|
||||
result.Value.Any(r => r.Children.Count != 0).Should().BeTrue();
|
||||
}
|
||||
}
|
||||
+13
-7
@@ -1,17 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Enums.FileSystem;
|
||||
using Lumina.Domain.Common.Enums.FileSystem;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate;
|
||||
using Lumina.Domain.Core.Aggregates.FileManagement.FileManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures;
|
||||
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="Directory"/> class.
|
||||
@@ -98,12 +98,18 @@ public class DirectoryFixture
|
||||
private Directory CreateNestedDirectory(int currentDepth, int maxDepth, int maxChildrenPerDirectory)
|
||||
{
|
||||
List<FileSystemItem> childItems = [];
|
||||
|
||||
// ensure we create at least one child if we haven't reached max depth
|
||||
if (currentDepth < maxDepth)
|
||||
{
|
||||
int childCount = _faker.Random.Int(0, maxChildrenPerDirectory);
|
||||
// force at least 1 child, up to maxChildrenPerDirectory
|
||||
int childCount = _faker.Random.Int(1, maxChildrenPerDirectory);
|
||||
for (int i = 0; i < childCount; i++)
|
||||
childItems.Add(CreateNestedDirectory(currentDepth + 1, maxDepth, maxChildrenPerDirectory));
|
||||
{
|
||||
Directory childDirectory = CreateNestedDirectory(currentDepth + 1, maxDepth, maxChildrenPerDirectory);
|
||||
ErrorOr<Updated> addResult = childDirectory.SetParent(childDirectory);
|
||||
if (!addResult.IsError)
|
||||
childItems.Add(childDirectory);
|
||||
}
|
||||
}
|
||||
return CreateDirectory(childItems: childItems);
|
||||
}
|
||||
+2
-2
@@ -1,12 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.FileManagement;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.FileManagement.Directories.Fixtures;
|
||||
namespace Lumina.Application.UnitTests.Core.FileSystemManagement.Directories.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="DirectoryResponse"/> class.
|
||||
Loaded 100 of 853 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user