From 5aa7a5f6725d740f553b5edd2349c382f19017e9 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 16 Nov 2024 15:49:24 +0200 Subject: [PATCH] Adds authentication support for integration testing --- .../CheckPathExists/CheckPathExistsQuery.cs | 5 +- .../CheckPathExistsQueryHandler.cs | 9 +- .../CheckPathExistsEndpoint.cs | 6 +- .../Common/Fixtures/JwtFixture.cs | 49 -------- .../Setup/AuthenticatedLuminaApiFactory.cs | 116 ++++++++++++++++++ .../Common/Setup/LuminaApiFactory.cs | 5 + .../GetDirectoriesEndpointTests.cs | 27 +++- .../GetDirectoryTreeEndpointTests.cs | 25 +++- .../GetTreeDirectoriesEndpointTests.cs | 25 +++- .../Drives/GetDrivesEndpointTests.cs | 27 +++- .../FileSystem/GetTypeEndpointTests.cs | 25 +++- .../Files/GetFilesEndpointTests.cs | 25 +++- .../Files/GetTreeFilesEndpointTests.cs | 25 +++- .../Path/CheckPathExistsEndpointTests.cs | 46 +++++-- .../Path/CombinePathEndpointTests.cs | 25 +++- .../Path/GetPathParentEndpointTests.cs | 25 +++- .../Path/GetPathRootEndpointTests.cs | 24 +++- .../Path/GetPathSeparatorEndpointTests.cs | 25 +++- .../Path/SplitPathEndpointTests.cs | 25 +++- .../Path/ValidatePathEndpointTests.cs | 25 +++- .../Thumbnails/GetThumbnailEndpointTests.cs | 25 +++- .../CheckInitializationEndpointTests.cs | 36 +++--- .../SetupApplicationEndpointTests.cs | 26 ++-- .../ChangePasswordEndpointTests.cs | 70 ++++------- .../Authentication/LoginEndpointTests.cs | 26 ++-- .../RecoverPasswordEndpointTests.cs | 26 ++-- .../Authentication/RegisterEndpointTests.cs | 26 ++-- .../BookLibrary/Books/AddBookEndpointTests.cs | 25 +++- .../Books/GetBooksEndpointTests.cs | 25 +++- .../Common/Setup/LuminaApiFactory.cs | 8 +- .../Authentication/AuthChangePasswordTests.cs | 5 - .../CheckPathExistsQueryHandlerTests.cs | 31 +++-- .../Path/CheckPathExistsEndpointTests.cs | 5 +- 33 files changed, 671 insertions(+), 227 deletions(-) delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Fixtures/JwtFixture.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs index 13cbfbb5..9c3db95b 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Mediator; using System.Diagnostics; @@ -13,6 +14,6 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathEx /// Whether to include hidden file system elements or not. [DebuggerDisplay("Path: {Path}, IncludeHiddenElements: {IncludeHiddenElements}")] public record CheckPathExistsQuery( - string? Path, + string? Path, bool IncludeHiddenElements -) : IRequest; +) : IRequest>; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs index 7004ac97..df02b2eb 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Mediator; @@ -11,7 +12,7 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathEx /// /// Handler for the query to check the existence a file system path. /// -public class CheckPathExistsQueryHandler : IRequestHandler +public class CheckPathExistsQueryHandler : IRequestHandler> { private readonly IPathService _pathService; @@ -30,10 +31,10 @@ public class CheckPathExistsQueryHandler : IRequestHandlerThe query containing the request. /// Cancellation token that can be used to stop the execution. /// - /// if the specified path exists, otherwise. + /// An containing either if the specified path exists, if it doesn't, or an error message. /// - public ValueTask Handle(CheckPathExistsQuery request, CancellationToken cancellationToken) + public ValueTask> Handle(CheckPathExistsQuery request, CancellationToken cancellationToken) { - return ValueTask.FromResult(new PathExistsResponse(_pathService.Exists(request.Path!, request.IncludeHiddenElements))); + return ValueTask.FromResult(ErrorOrFactory.From(new PathExistsResponse(_pathService.Exists(request.Path!, request.IncludeHiddenElements)))); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs index 685481eb..8f5317d0 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; using FastEndpoints; using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Contracts.Requests.FileSystemManagement.Path; @@ -37,7 +38,6 @@ public class CheckPathExistsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CheckPathExistsRequest request, CancellationToken cancellationToken) { - PathExistsResponse result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); - return TypedResults.Ok(result); + ErrorOr result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Fixtures/JwtFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Fixtures/JwtFixture.cs deleted file mode 100644 index 84a5c625..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Fixtures/JwtFixture.cs +++ /dev/null @@ -1,49 +0,0 @@ -#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; - -/// -/// Provides JWT token generation functionality for testing purposes. -/// -[ExcludeFromCodeCoverage] -public class JwtFixture -{ - private static readonly string s_secretKey = "test-key-thats-at-least-32-chars-long-for-jwt"; - - /// - /// Generates a JWT token for testing with the specified username and optional roles. - /// - /// The username to include in the token claims. - /// Optional array of roles to include in the token claims. - /// A JWT token string that can be used for authentication in tests. - public static string GenerateJwtToken(string username, string[]? roles = null) - { - byte[] key = Encoding.ASCII.GetBytes(s_secretKey); - List 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); - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs new file mode 100644 index 00000000..1b3a50a8 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +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 Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; + +// +/// Factory that extends to provide authenticated HTTP clients for testing. +/// +[ExcludeFromCodeCoverage] +public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable +{ + private readonly HashService _hashService; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Gets the username of the currently created test user. + /// + public string? TestUsername { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public AuthenticatedLuminaApiFactory() + { + _hashService = new HashService(); + } + + /// + /// Creates an HTTP client with authentication headers and a test user + /// + /// An HTTP client configured with auth headers + public async Task CreateAuthenticatedClientAsync() + { + HttpClient client = CreateClient(); + TestUsername = $"testuser_{Guid.NewGuid()}"; + + // add the X-Forwarded-For header + client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}"); + + // perform authentication + await CreateAndAuthenticateUser(client); + + return client; + } + + /// + /// Creates and authenticates a test user. + /// + /// The HTTP client to configure with auth. + /// The created user entity. + private async Task CreateAndAuthenticateUser(HttpClient client) + { + using IServiceScope scope = Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + // 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(content, _jsonOptions); + + // set auth header for subsequent requests + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token); + + return user; + } + + /// + /// Disposes API factory resources. + /// + public new void Dispose() + { + using IServiceScope scope = Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs index e0890627..75d1faca 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs @@ -25,6 +25,9 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable { private readonly SqliteConnection _connection; private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; + private static byte s_IpClass = 25; + + public static byte IpClass => s_IpClass++; /// /// Initializes a new instance of the class. @@ -54,6 +57,8 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable config.AddInMemoryCollection(initialData: new Dictionary { ["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt", + ["JwtSettings:Issuer"] = "test-issuer", + ["JwtSettings:Audience"] = "test-audience", ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key }); }); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs index 3bc59acd..44fd7b96 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -23,9 +23,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetDirectoriesEndpointTests : IClassFixture +public class GetDirectoriesEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -38,9 +39,18 @@ public class GetDirectoriesEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetDirectoriesEndpointTests(LuminaApiFactory apiFactory) + public GetDirectoriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -59,10 +69,10 @@ public class GetDirectoriesEndpointTests : IClassFixture HttpResponseMessage response = await _client.GetAsync($"/api/v1/directories/get-directories?path={encodedPath}&includeHiddenElements={includeHiddenElements}"); // Assert + string content = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); List? directories = JsonSerializer.Deserialize>(content, _jsonOptions); directories.Should().NotBeNull(); @@ -201,4 +211,13 @@ public class GetDirectoriesEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs index cd0c8f84..2aa8a0cd 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoryTreeEndpointTests.cs @@ -24,9 +24,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetDirectoryTreeEndpointTests : IClassFixture +public class GetDirectoryTreeEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -39,9 +40,18 @@ public class GetDirectoryTreeEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetDirectoryTreeEndpointTests(LuminaApiFactory apiFactory) + public GetDirectoryTreeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -408,4 +418,13 @@ public class GetDirectoryTreeEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs index eb32d295..9fd8be30 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetTreeDirectoriesEndpointTests.cs @@ -24,9 +24,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetTreeDirectoriesEndpointTests : IClassFixture +public class GetTreeDirectoriesEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -39,9 +40,18 @@ public class GetTreeDirectoriesEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetTreeDirectoriesEndpointTests(LuminaApiFactory apiFactory) + public GetTreeDirectoriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -244,4 +254,13 @@ public class GetTreeDirectoriesEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs index 4cc349f2..fa0c6102 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FluentAssertions; -using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.Common.Enums.FileSystem; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -20,9 +20,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetDrivesEndpointTests : IClassFixture +public class GetDrivesEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -31,13 +32,31 @@ public class GetDrivesEndpointTests : IClassFixture }; private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } + /// /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetDrivesEndpointTests(LuminaApiFactory apiFactory) + public GetDrivesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; } [Fact] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs index e6941eea..d50552f6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs @@ -19,9 +19,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetTypeEndpointTests : IClassFixture +public class GetTypeEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -33,9 +34,18 @@ public class GetTypeEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetTypeEndpointTests(LuminaApiFactory apiFactory) + public GetTypeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -86,4 +96,13 @@ public class GetTypeEndpointTests : IClassFixture // Assert await act.Should().NotThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs index 189d8b77..281beb5b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs @@ -23,9 +23,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetFilesEndpointTests : IClassFixture +public class GetFilesEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -38,9 +39,18 @@ public class GetFilesEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetFilesEndpointTests(LuminaApiFactory apiFactory) + public GetFilesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -240,4 +250,13 @@ public class GetFilesEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs index 4c2c2f7b..0c0963b5 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs @@ -23,9 +23,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetTreeFilesEndpointTests : IClassFixture +public class GetTreeFilesEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -38,9 +39,18 @@ public class GetTreeFilesEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetTreeFilesEndpointTests(LuminaApiFactory apiFactory) + public GetTreeFilesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -240,4 +250,13 @@ public class GetTreeFilesEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs index d54789f9..9846e247 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -2,7 +2,9 @@ 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; @@ -18,9 +20,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class CheckPathExistsEndpointTests : IClassFixture +public class CheckPathExistsEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -32,9 +35,18 @@ public class CheckPathExistsEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public CheckPathExistsEndpointTests(LuminaApiFactory apiFactory) + public CheckPathExistsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -72,7 +84,7 @@ public class CheckPathExistsEndpointTests : IClassFixture } [Fact] - public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnOkResultWithExistsFalse() + public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult() { // Arrange string path = ""; @@ -81,11 +93,20 @@ public class CheckPathExistsEndpointTests : IClassFixture HttpResponseMessage response = await _client.GetAsync($"/api/v1/path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=false"); // Assert - response.StatusCode.Should().Be(HttpStatusCode.OK); + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); string content = await response.Content.ReadAsStringAsync(); - PathExistsResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); - result.Should().NotBeNull(); - result!.Exists.Should().BeFalse(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(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/check-path-exists"); + 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? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]); } [Fact] @@ -123,4 +144,13 @@ public class CheckPathExistsEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs index 87af0661..389944f5 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs @@ -20,9 +20,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class CombinePathEndpointTests : IClassFixture +public class CombinePathEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -34,9 +35,18 @@ public class CombinePathEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public CombinePathEndpointTests(LuminaApiFactory apiFactory) + public CombinePathEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -120,4 +130,13 @@ public class CombinePathEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs index 3f1cfec4..9a16e9c6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs @@ -22,9 +22,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetPathParentEndpointTests : IClassFixture +public class GetPathParentEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -37,9 +38,18 @@ public class GetPathParentEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetPathParentEndpointTests(LuminaApiFactory apiFactory) + public GetPathParentEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -188,4 +198,13 @@ public class GetPathParentEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs index ea284760..7d424466 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs @@ -21,9 +21,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetPathRootEndpointTests : IClassFixture +public class GetPathRootEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -35,9 +36,18 @@ public class GetPathRootEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetPathRootEndpointTests(LuminaApiFactory apiFactory) + public GetPathRootEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -146,4 +156,12 @@ public class GetPathRootEndpointTests : IClassFixture await act.Should().ThrowAsync(); } + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs index b1b241d6..2fcf902f 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs @@ -18,9 +18,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetPathSeparatorEndpointTests : IClassFixture +public class GetPathSeparatorEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -32,9 +33,18 @@ public class GetPathSeparatorEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetPathSeparatorEndpointTests(LuminaApiFactory apiFactory) + public GetPathSeparatorEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -102,4 +112,13 @@ public class GetPathSeparatorEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs index 41b9fe0e..8ee7d597 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs @@ -21,9 +21,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class SplitPathEndpointTests : IClassFixture +public class SplitPathEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -35,9 +36,18 @@ public class SplitPathEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public SplitPathEndpointTests(LuminaApiFactory apiFactory) + public SplitPathEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -129,4 +139,13 @@ public class SplitPathEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs index ddc0202f..cdacc41b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -18,9 +18,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class ValidatePathEndpointTests : IClassFixture +public class ValidatePathEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -32,9 +33,18 @@ public class ValidatePathEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public ValidatePathEndpointTests(LuminaApiFactory apiFactory) + public ValidatePathEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -107,4 +117,13 @@ public class ValidatePathEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs index 67a97b4d..1051d237 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs @@ -20,9 +20,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetThumbnailEndpointTests : IClassFixture, IClassFixture +public class GetThumbnailEndpointTests : IClassFixture, IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -36,12 +37,21 @@ public class GetThumbnailEndpointTests : IClassFixture, IClass /// /// Injected in-memory API factory. /// Fixture for creating and managing test images. - public GetThumbnailEndpointTests(LuminaApiFactory apiFactory, TestImageFixture imageFixture) + public GetThumbnailEndpointTests(AuthenticatedLuminaApiFactory apiFactory, TestImageFixture imageFixture) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; _testImagePath = imageFixture.ImagePath; } + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + [Fact] public async Task ExecuteAsync_WhenCalledWithValidPathAndQuality_ShouldReturnOkResultWithThumbnail() { @@ -152,4 +162,13 @@ public class GetThumbnailEndpointTests : IClassFixture, IClass // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs index f2220547..87c481bb 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -5,6 +5,7 @@ using Lumina.Contracts.Responses.UsersManagement; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; @@ -23,10 +24,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Maintenance.Ap /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class CheckInitializationEndpointTests : IClassFixture, IDisposable +public class CheckInitializationEndpointTests : IClassFixture, IAsyncLifetime { - private readonly LuminaApiFactory _apiFactory; - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true, @@ -38,13 +39,22 @@ public class CheckInitializationEndpointTests : IClassFixture, /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public CheckInitializationEndpointTests(LuminaApiFactory apiFactory) + public CheckInitializationEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { - _apiFactory = apiFactory; _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; _testUsername = $"testuser_{Guid.NewGuid()}"; } + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = _apiFactory.CreateClient(); + await Task.CompletedTask; + } + [Fact] public async Task ExecuteAsync_WhenNoUsersExist_ShouldReturnNotInitialized() { @@ -117,16 +127,12 @@ public class CheckInitializationEndpointTests : IClassFixture, return user; } - public void Dispose() + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - - UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); - if (user is not null) - { - dbContext.Users.Remove(user); - dbContext.SaveChanges(); - } + _apiFactory.Dispose(); + return Task.CompletedTask; } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs index 180e5594..6d40f9f5 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -26,10 +26,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Maintenance.Ap /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class SetupApplicationEndpointTests : IClassFixture, IDisposable +public class SetupApplicationEndpointTests : IClassFixture, IAsyncLifetime { - private readonly LuminaApiFactory _apiFactory; - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true, @@ -41,13 +41,22 @@ public class SetupApplicationEndpointTests : IClassFixture, ID /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public SetupApplicationEndpointTests(LuminaApiFactory apiFactory) + public SetupApplicationEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { - _apiFactory = apiFactory; _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; _testUsername = $"testuser_{Guid.NewGuid()}"; } + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = _apiFactory.CreateClient(); + await Task.CompletedTask; + } + [Fact] public async Task ExecuteAsync_WhenCalledWithValidRequestAnd2FA_ShouldSetupApplicationSuccessfully() { @@ -172,7 +181,10 @@ public class SetupApplicationEndpointTests : IClassFixture, ID return user; } - public void Dispose() + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -181,7 +193,7 @@ public class SetupApplicationEndpointTests : IClassFixture, ID if (user is not null) { dbContext.Users.Remove(user); - dbContext.SaveChanges(); + await dbContext.SaveChangesAsync(); } } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs index e6cb419c..80c6dec1 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs @@ -4,8 +4,6 @@ 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; @@ -15,7 +13,6 @@ 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; @@ -29,42 +26,41 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagemen /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class ChangePasswordEndpointTests : IClassFixture, IDisposable +public class ChangePasswordEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HashService _hashService; - private readonly LuminaApiFactory _apiFactory; - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true, Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } }; - private readonly string _testUsername; /// /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public ChangePasswordEndpointTests(LuminaApiFactory apiFactory) + public ChangePasswordEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { - _apiFactory = apiFactory; _client = apiFactory.CreateClient(); - _hashService = new HashService(); - _testUsername = $"testuser_{Guid.NewGuid()}"; + _apiFactory = apiFactory; + } - // Set authorization header with unique username - string token = JwtFixture.GenerateJwtToken(_testUsername, ["User"]); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldChangePasswordSuccessfully() { // Arrange - UserEntity user = await CreateTestUser(); ChangePasswordRequest request = new( - Username: user.Username, - CurrentPassword: "OldPass123!", + Username: _apiFactory.TestUsername, + CurrentPassword: "TestPass123!", NewPassword: "NewPass123!", NewPasswordConfirm: "NewPass123!" ); @@ -73,10 +69,10 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); // Assert + string content = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); response.StatusCode.Should().Be(HttpStatusCode.OK); - string content = await response.Content.ReadAsStringAsync(); ChangePasswordResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); result.Should().NotBeNull(); @@ -87,9 +83,8 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis public async Task ExecuteAsync_WhenPasswordsDoNotMatch_ShouldReturnValidationError() { // Arrange - UserEntity user = await CreateTestUser(); ChangePasswordRequest request = new( - Username: user.Username, + Username: _apiFactory.TestUsername, CurrentPassword: "OldPass123!", NewPassword: "NewPass123!", NewPasswordConfirm: "DifferentPass123!" @@ -147,9 +142,8 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis public async Task ExecuteAsync_WhenCurrentPasswordIsIncorrect_ShouldReturnForbidden() { // Arrange - UserEntity user = await CreateTestUser(); ChangePasswordRequest request = new( - Username: user.Username, + Username: _apiFactory.TestUsername, CurrentPassword: "WrongPass123!", NewPassword: "NewPass123!", NewPasswordConfirm: "NewPass123!" @@ -202,9 +196,8 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException() { // Arrange - UserEntity user = await CreateTestUser(); ChangePasswordRequest request = new( - Username: user.Username, + Username: _apiFactory.TestUsername, CurrentPassword: "OldPass123!", NewPassword: "NewPass123!", NewPasswordConfirm: "NewPass123!" @@ -222,34 +215,19 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis await act.Should().ThrowAsync(); } - private async Task CreateTestUser() + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - 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(); - - UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _apiFactory.TestUsername!); if (user is not null) { dbContext.Users.Remove(user); - dbContext.SaveChanges(); + await dbContext.SaveChangesAsync(); } } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs index 7f468272..4e248aac 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs @@ -29,13 +29,13 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagemen /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class LoginEndpointTests : IClassFixture, IDisposable +public class LoginEndpointTests : IClassFixture, IAsyncLifetime { + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; 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, @@ -47,10 +47,10 @@ public class LoginEndpointTests : IClassFixture, IDisposable /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public LoginEndpointTests(LuminaApiFactory apiFactory) + public LoginEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { - _apiFactory = apiFactory; _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; _hashService = new HashService(); _totpTokenGenerator = new TotpTokenGenerator(); _testUsername = $"testuser_{Guid.NewGuid()}"; @@ -59,6 +59,15 @@ public class LoginEndpointTests : IClassFixture, IDisposable _cryptographyService = scope.ServiceProvider.GetRequiredService(); } + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = _apiFactory.CreateClient(); + await Task.CompletedTask; + } + [Fact] public async Task ExecuteAsync_WhenCalledWithValidCredentials_ShouldLoginSuccessfully() { @@ -304,7 +313,10 @@ public class LoginEndpointTests : IClassFixture, IDisposable return user; } - public void Dispose() + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -313,7 +325,7 @@ public class LoginEndpointTests : IClassFixture, IDisposable if (user is not null) { dbContext.Users.Remove(user); - dbContext.SaveChanges(); + await dbContext.SaveChangesAsync(); } } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs index 1b8cc3b7..38b47cd9 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -31,13 +31,13 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagemen /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class RecoverPasswordEndpointTests : IClassFixture, IDisposable +public class RecoverPasswordEndpointTests : IClassFixture, IAsyncLifetime { + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; 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, @@ -49,10 +49,10 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public RecoverPasswordEndpointTests(LuminaApiFactory apiFactory) + public RecoverPasswordEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { - _apiFactory = apiFactory; _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; _hashService = new HashService(); _totpTokenGenerator = new TotpTokenGenerator(); _testUsername = $"testuser_{Guid.NewGuid()}"; @@ -62,6 +62,15 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi _cryptographyService = scope.ServiceProvider.GetRequiredService(); } + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = _apiFactory.CreateClient(); + await Task.CompletedTask; + } + [Fact] public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldResetPassword() { @@ -324,7 +333,10 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi return user; } - public void Dispose() + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -333,7 +345,7 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi if (user is not null) { dbContext.Users.Remove(user); - dbContext.SaveChanges(); + await dbContext.SaveChangesAsync(); } } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs index 83eeb4b2..963dc51e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs @@ -26,10 +26,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagemen /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class RegisterEndpointTests : IClassFixture, IDisposable +public class RegisterEndpointTests : IClassFixture, IAsyncLifetime { - private readonly LuminaApiFactory _apiFactory; - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true, @@ -41,13 +41,22 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public RegisterEndpointTests(LuminaApiFactory apiFactory) + public RegisterEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { - _apiFactory = apiFactory; _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; _testUsername = $"testuser_{Guid.NewGuid()}"; } + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = _apiFactory.CreateClient(); + await Task.CompletedTask; + } + [Fact] public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldRegisterUserSuccessfully() { @@ -190,7 +199,10 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl return user; } - public void Dispose() + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -199,7 +211,7 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl if (user is not null) { dbContext.Users.Remove(user); - dbContext.SaveChanges(); + await dbContext.SaveChangesAsync(); } } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs index 1f53e632..675c7ec6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/AddBookEndpointTests.cs @@ -27,9 +27,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContent /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class AddBookEndpointTests : IClassFixture +public class AddBookEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -45,12 +46,21 @@ public class AddBookEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public AddBookEndpointTests(LuminaApiFactory apiFactory) + public AddBookEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; _requestBookFixture = new AddBookRequestFixture(); } + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + [Fact] public async Task AddBook_WhenCalledWithValidData_ShouldAddBook() { @@ -1595,4 +1605,13 @@ public class AddBookEndpointTests : IClassFixture response.StatusCode.Should().Be(HttpStatusCode.Created); bookResponse.Should().NotBeNull(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs index 35039b04..53150564 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/WrittenContentLibrary/BookLibrary/Books/GetBooksEndpointTests.cs @@ -20,9 +20,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContent /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] -public class GetBooksEndpointTests : IClassFixture +public class GetBooksEndpointTests : IClassFixture, IAsyncLifetime { - private readonly HttpClient _client; + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { ReferenceHandler = ReferenceHandler.Preserve, @@ -34,9 +35,18 @@ public class GetBooksEndpointTests : IClassFixture /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public GetBooksEndpointTests(LuminaApiFactory apiFactory) + public GetBooksEndpointTests(AuthenticatedLuminaApiFactory apiFactory) { _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); } [Fact] @@ -83,4 +93,13 @@ public class GetBooksEndpointTests : IClassFixture // Assert await act.Should().ThrowAsync(); } + + /// + /// Disposes API factory resources. + /// + public Task DisposeAsync() + { + _apiFactory.Dispose(); + return Task.CompletedTask; + } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs index 59b90215..ff96ed28 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs @@ -22,7 +22,7 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable { private readonly SqliteConnection _connection; private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; - + /// /// Initializes a new instance of the class. /// @@ -52,6 +52,8 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable { ["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt", ["JwtSettings:ExpiryMinutes"] = "15", // control the expiry time during tests + ["JwtSettings:Issuer"] = "Lumina", + ["JwtSettings:Audience"] = "Lumina", ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key }); }); @@ -72,8 +74,8 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, - ValidIssuer = "test-issuer", - ValidAudience = "test-audience", + ValidIssuer = "Lumina", + ValidAudience = "Lumina", IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("test-key-thats-at-least-32-chars-long-for-jwt")) }; }); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs index 489480f5..d32b700d 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs @@ -1,23 +1,18 @@ #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; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs index 5940d286..f20173e9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Pahs/Queries/CheckPathExists/CheckPathExistsQueryHandlerTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; using FluentAssertions; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Queries.CheckPathExists.Fixtures; @@ -38,10 +39,11 @@ public class CheckPathExistsQueryHandlerTests _mockPathService.Exists(query.Path!).Returns(true); // Act - PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.Handle(query, CancellationToken.None); // Assert - result.Exists.Should().BeTrue(); + result.IsError.Should().BeFalse(); + result.Value.Exists.Should().BeTrue(); _mockPathService.Received(1).Exists(query.Path!); } @@ -53,10 +55,11 @@ public class CheckPathExistsQueryHandlerTests _mockPathService.Exists(query.Path!).Returns(true); // Act - PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.Handle(query, CancellationToken.None); // Assert - result.Exists.Should().BeTrue(); + result.IsError.Should().BeFalse(); + result.Value.Exists.Should().BeTrue(); _mockPathService.Received(1).Exists(query.Path!); } @@ -68,10 +71,11 @@ public class CheckPathExistsQueryHandlerTests _mockPathService.Exists(query.Path!, false).Returns(false); // Act - PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.Handle(query, CancellationToken.None); // Assert - result.Exists.Should().BeFalse(); + result.IsError.Should().BeFalse(); + result.Value.Exists.Should().BeFalse(); _mockPathService.Received(1).Exists(query.Path!, false); } @@ -83,10 +87,11 @@ public class CheckPathExistsQueryHandlerTests _mockPathService.Exists(query.Path!).Returns(false); // Act - PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.Handle(query, CancellationToken.None); // Assert - result.Exists.Should().BeFalse(); + result.IsError.Should().BeFalse(); + result.Value.Exists.Should().BeFalse(); _mockPathService.Received(1).Exists(query.Path!); } @@ -98,10 +103,11 @@ public class CheckPathExistsQueryHandlerTests _mockPathService.Exists(Arg.Any(), Arg.Any()).Returns(false); // Act - PathExistsResponse result = await _sut.Handle(query, CancellationToken.None); + ErrorOr result = await _sut.Handle(query, CancellationToken.None); // Assert - result.Exists.Should().BeFalse(); + result.IsError.Should().BeFalse(); + result.Value.Exists.Should().BeFalse(); _mockPathService.Received(1).Exists(Arg.Any(), Arg.Any()); } @@ -114,10 +120,11 @@ public class CheckPathExistsQueryHandlerTests CancellationToken cancellationToken = new(true); // Act - PathExistsResponse result = await _sut.Handle(query, cancellationToken); + ErrorOr result = await _sut.Handle(query, CancellationToken.None); // Assert - result.Exists.Should().BeTrue(); + result.IsError.Should().BeFalse(); + result.Value.Exists.Should().BeTrue(); _mockPathService.Received(1).Exists(query.Path!); } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs index fcca5a67..3b1bbc22 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using ErrorOr; using FastEndpoints; using FluentAssertions; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; @@ -84,12 +85,12 @@ public class CheckPathExistsEndpointTests TaskCompletionSource cancellationRequested = new(); _mockSender.Send(Arg.Any(), Arg.Any()) - .Returns(callInfo => new ValueTask(Task.Run(async () => + .Returns(callInfo => new ValueTask>(Task.Run(async () => { operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return new PathExistsResponse(true); + return ErrorOrFactory.From(new PathExistsResponse(true)); }, callInfo.Arg()))); // Act