Merge pull request #70 from BinaryAlley/feature/add-authentication-support-for-integration-testing

Adds authentication support for integration testing
This commit is contained in:
BinaryAlley authored and GitHub committed 2024-11-16 15:53:42 +02:00
commit a3bc4882b3
33 files changed
+671 -227

No files matched your search

@@ -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
/// <param name="IncludeHiddenElements">Whether to include hidden file system elements or not.</param>
[DebuggerDisplay("Path: {Path}, IncludeHiddenElements: {IncludeHiddenElements}")]
public record CheckPathExistsQuery(
string? Path,
string? Path,
bool IncludeHiddenElements
) : IRequest<PathExistsResponse>;
) : IRequest<ErrorOr<PathExistsResponse>>;
@@ -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
/// <summary>
/// Handler for the query to check the existence a file system path.
/// </summary>
public class CheckPathExistsQueryHandler : IRequestHandler<CheckPathExistsQuery, PathExistsResponse>
public class CheckPathExistsQueryHandler : IRequestHandler<CheckPathExistsQuery, ErrorOr<PathExistsResponse>>
{
private readonly IPathService _pathService;
@@ -30,10 +31,10 @@ public class CheckPathExistsQueryHandler : IRequestHandler<CheckPathExistsQuery,
/// <param name="request">The query containing the request.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// <see langword="true"/> if the specified path exists, <see langword="false"/> otherwise.
/// An <see cref="ErrorOr{TValue}"/> containing either <see langword="true"/> if the specified path exists, <see langword="false"/> if it doesn't, or an error message.
/// </returns>
public ValueTask<PathExistsResponse> Handle(CheckPathExistsQuery request, CancellationToken cancellationToken)
public ValueTask<ErrorOr<PathExistsResponse>> 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))));
}
}
@@ -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 : BaseEndpoint<CheckPathExistsRequest, IRes
Verbs(Http.GET);
Routes(ApiRoutes.Path.CHECK_PATH_EXISTS);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
@@ -48,7 +48,7 @@ public class CheckPathExistsEndpoint : BaseEndpoint<CheckPathExistsRequest, IRes
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(CheckPathExistsRequest request, CancellationToken cancellationToken)
{
PathExistsResponse result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return TypedResults.Ok(result);
ErrorOr<PathExistsResponse> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <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);
}
}
@@ -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;
// <summary>
/// Factory that extends <see cref="LuminaApiFactory"/> to provide authenticated HTTP clients for testing.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
{
private readonly HashService _hashService;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Gets the username of the currently created test user.
/// </summary>
public string? TestUsername { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="AuthenticatedLuminaApiFactory"/> class.
/// </summary>
public AuthenticatedLuminaApiFactory()
{
_hashService = new HashService();
}
/// <summary>
/// Creates an HTTP client with authentication headers and a test user
/// </summary>
/// <returns>An HTTP client configured with auth headers</returns>
public async Task<HttpClient> 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;
}
/// <summary>
/// Creates and authenticates a test user.
/// </summary>
/// <param name="client">The HTTP client to configure with auth.</param>
/// <returns>The created user entity.</returns>
private async Task<UserEntity> CreateAndAuthenticateUser(HttpClient client)
{
using IServiceScope scope = 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;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public new void Dispose()
{
using IServiceScope scope = 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();
}
}
}
@@ -25,6 +25,9 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
{
private readonly SqliteConnection _connection;
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
private static byte s_IpClass = 25;
public static byte IpClass => s_IpClass++;
/// <summary>
/// Initializes a new instance of the <see cref="LuminaApiFactory"/> class.
@@ -54,6 +57,8 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
{
["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
});
});
@@ -23,9 +23,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="GetDirectoriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoriesEndpointTests : IClassFixture<LuminaApiFactory>
public class GetDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="GetDirectoriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDirectoriesEndpointTests(LuminaApiFactory apiFactory)
public GetDirectoriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -59,10 +69,10 @@ public class GetDirectoriesEndpointTests : IClassFixture<LuminaApiFactory>
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<DirectoryResponse>? directories = JsonSerializer.Deserialize<List<DirectoryResponse>>(content, _jsonOptions);
directories.Should().NotBeNull();
@@ -201,4 +211,13 @@ public class GetDirectoriesEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -24,9 +24,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="GetDirectoryTreeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDirectoryTreeEndpointTests : IClassFixture<LuminaApiFactory>
public class GetDirectoryTreeEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDirectoryTreeEndpointTests(LuminaApiFactory apiFactory)
public GetDirectoryTreeEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -408,4 +418,13 @@ public class GetDirectoryTreeEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -24,9 +24,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="GetTreeDirectoriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeDirectoriesEndpointTests : IClassFixture<LuminaApiFactory>
public class GetTreeDirectoriesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTreeDirectoriesEndpointTests(LuminaApiFactory apiFactory)
public GetTreeDirectoriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -244,4 +254,13 @@ public class GetTreeDirectoriesEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -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 <see cref="GetDrivesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDrivesEndpointTests : IClassFixture<LuminaApiFactory>
public class GetDrivesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
};
private static readonly bool s_isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
/// <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)
public GetDrivesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
[Fact]
@@ -19,9 +19,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="GetTypeEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTypeEndpointTests : IClassFixture<LuminaApiFactory>
public class GetTypeEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="GetTypeEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTypeEndpointTests(LuminaApiFactory apiFactory)
public GetTypeEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -86,4 +96,13 @@ public class GetTypeEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().NotThrowAsync();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -23,9 +23,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="GetFilesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFilesEndpointTests : IClassFixture<LuminaApiFactory>
public class GetFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="GetFilesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetFilesEndpointTests(LuminaApiFactory apiFactory)
public GetFilesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -240,4 +250,13 @@ public class GetFilesEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -23,9 +23,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="GetTreeFilesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTreeFilesEndpointTests : IClassFixture<LuminaApiFactory>
public class GetTreeFilesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="GetTreeFilesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTreeFilesEndpointTests(LuminaApiFactory apiFactory)
public GetTreeFilesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -240,4 +250,13 @@ public class GetTreeFilesEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -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 <see cref="CheckPathExistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckPathExistsEndpointTests : IClassFixture<LuminaApiFactory>
public class CheckPathExistsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="CheckPathExistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CheckPathExistsEndpointTests(LuminaApiFactory apiFactory)
public CheckPathExistsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -72,7 +84,7 @@ public class CheckPathExistsEndpointTests : IClassFixture<LuminaApiFactory>
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnOkResultWithExistsFalse()
public async Task ExecuteAsync_WhenCalledWithEmptyPath_ShouldReturnValidationProblemResult()
{
// Arrange
string path = "";
@@ -81,11 +93,20 @@ public class CheckPathExistsEndpointTests : IClassFixture<LuminaApiFactory>
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<PathExistsResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.Exists.Should().BeFalse();
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/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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().BeEquivalentTo(["PathCannotBeEmpty"]);
}
[Fact]
@@ -123,4 +144,13 @@ public class CheckPathExistsEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -20,9 +20,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="CombinePathEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CombinePathEndpointTests : IClassFixture<LuminaApiFactory>
public class CombinePathEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="CombinePathEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CombinePathEndpointTests(LuminaApiFactory apiFactory)
public CombinePathEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -120,4 +130,13 @@ public class CombinePathEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -22,9 +22,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="GetPathParentEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathParentEndpointTests : IClassFixture<LuminaApiFactory>
public class GetPathParentEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="GetPathParentEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPathParentEndpointTests(LuminaApiFactory apiFactory)
public GetPathParentEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -188,4 +198,13 @@ public class GetPathParentEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -21,9 +21,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="GetPathRootEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathRootEndpointTests : IClassFixture<LuminaApiFactory>
public class GetPathRootEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="GetPathRootEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPathRootEndpointTests(LuminaApiFactory apiFactory)
public GetPathRootEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -146,4 +156,12 @@ public class GetPathRootEndpointTests : IClassFixture<LuminaApiFactory>
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -18,9 +18,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="GetPathSeparatorEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathSeparatorEndpointTests : IClassFixture<LuminaApiFactory>
public class GetPathSeparatorEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="GetPathSeparatorEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPathSeparatorEndpointTests(LuminaApiFactory apiFactory)
public GetPathSeparatorEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -102,4 +112,13 @@ public class GetPathSeparatorEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -21,9 +21,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="SplitPathEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SplitPathEndpointTests : IClassFixture<LuminaApiFactory>
public class SplitPathEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="SplitPathEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SplitPathEndpointTests(LuminaApiFactory apiFactory)
public SplitPathEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -129,4 +139,13 @@ public class SplitPathEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -18,9 +18,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="ValidatePathEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidatePathEndpointTests : IClassFixture<LuminaApiFactory>
public class ValidatePathEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="ValidatePathEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ValidatePathEndpointTests(LuminaApiFactory apiFactory)
public ValidatePathEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -107,4 +117,13 @@ public class ValidatePathEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -20,9 +20,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.FileSystemMana
/// Contains integration tests for the <see cref="GetThumbnailEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailEndpointTests : IClassFixture<LuminaApiFactory>, IClassFixture<TestImageFixture>
public class GetThumbnailEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IClassFixture<TestImageFixture>, 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<LuminaApiFactory>, IClass
/// </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)
public GetThumbnailEndpointTests(AuthenticatedLuminaApiFactory apiFactory, TestImageFixture imageFixture)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
_testImagePath = imageFixture.ImagePath;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task ExecuteAsync_WhenCalledWithValidPathAndQuality_ShouldReturnOkResultWithThumbnail()
{
@@ -152,4 +162,13 @@ public class GetThumbnailEndpointTests : IClassFixture<LuminaApiFactory>, IClass
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -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 <see cref="CheckInitializationEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckInitializationEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
public class CheckInitializationEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>,
/// Initializes a new instance of the <see cref="CheckInitializationEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CheckInitializationEndpointTests(LuminaApiFactory apiFactory)
public CheckInitializationEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
_testUsername = $"testuser_{Guid.NewGuid()}";
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
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<LuminaApiFactory>,
return user;
}
public void Dispose()
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
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();
}
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -26,10 +26,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Maintenance.Ap
/// Contains integration tests for the <see cref="SetupApplicationEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetupApplicationEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
public class SetupApplicationEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>, ID
/// Initializes a new instance of the <see cref="SetupApplicationEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetupApplicationEndpointTests(LuminaApiFactory apiFactory)
public SetupApplicationEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
_testUsername = $"testuser_{Guid.NewGuid()}";
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
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<LuminaApiFactory>, ID
return user;
}
public void Dispose()
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -181,7 +193,7 @@ public class SetupApplicationEndpointTests : IClassFixture<LuminaApiFactory>, ID
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
await dbContext.SaveChangesAsync();
}
}
}
@@ -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 <see cref="ChangePasswordEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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;
/// <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)
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);
/// <summary>
/// Initializes authenticated API client.
/// </summary>
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<LuminaApiFactory>, 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<ChangePasswordResponse>(content, _jsonOptions);
result.Should().NotBeNull();
@@ -87,9 +83,8 @@ public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, 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<LuminaApiFactory>, 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<LuminaApiFactory>, 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<LuminaApiFactory>, IDis
await act.Should().ThrowAsync<TaskCanceledException>();
}
private async Task<UserEntity> CreateTestUser()
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
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);
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _apiFactory.TestUsername!);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
await dbContext.SaveChangesAsync();
}
}
}
@@ -29,13 +29,13 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagemen
/// Contains integration tests for the <see cref="LoginEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>, IDisposable
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<LuminaApiFactory>, IDisposable
_cryptographyService = scope.ServiceProvider.GetRequiredService<ICryptographyService>();
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
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<LuminaApiFactory>, IDisposable
return user;
}
public void Dispose()
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -313,7 +325,7 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
await dbContext.SaveChangesAsync();
}
}
}
@@ -31,13 +31,13 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagemen
/// Contains integration tests for the <see cref="RecoverPasswordEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RecoverPasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>, IDi
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<LuminaApiFactory>, IDi
_cryptographyService = scope.ServiceProvider.GetRequiredService<ICryptographyService>();
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
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<LuminaApiFactory>, IDi
return user;
}
public void Dispose()
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -333,7 +345,7 @@ public class RecoverPasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDi
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
await dbContext.SaveChangesAsync();
}
}
}
@@ -26,10 +26,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagemen
/// Contains integration tests for the <see cref="RegisterEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>, IDisposabl
/// Initializes a new instance of the <see cref="RegisterEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RegisterEndpointTests(LuminaApiFactory apiFactory)
public RegisterEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
_testUsername = $"testuser_{Guid.NewGuid()}";
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
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<LuminaApiFactory>, IDisposabl
return user;
}
public void Dispose()
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -199,7 +211,7 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
await dbContext.SaveChangesAsync();
}
}
}
@@ -27,9 +27,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContent
/// Contains integration tests for the <see cref="AddBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>
public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="AddBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddBookEndpointTests(LuminaApiFactory apiFactory)
public AddBookEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
_requestBookFixture = new AddBookRequestFixture();
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task AddBook_WhenCalledWithValidData_ShouldAddBook()
{
@@ -1595,4 +1605,13 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>
response.StatusCode.Should().Be(HttpStatusCode.Created);
bookResponse.Should().NotBeNull();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -20,9 +20,10 @@ namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.WrittenContent
/// Contains integration tests for the <see cref="GetBooksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>
public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<LuminaApiFactory>
/// Initializes a new instance of the <see cref="GetBooksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetBooksEndpointTests(LuminaApiFactory apiFactory)
public GetBooksEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
@@ -83,4 +93,13 @@ public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public Task DisposeAsync()
{
_apiFactory.Dispose();
return Task.CompletedTask;
}
}
@@ -22,7 +22,7 @@ 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>
@@ -52,6 +52,8 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, 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<Program>, 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"))
};
});
@@ -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;
@@ -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<PathExistsResponse> 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<PathExistsResponse> 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<PathExistsResponse> 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<PathExistsResponse> 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<string>(), Arg.Any<bool>()).Returns(false);
// Act
PathExistsResponse result = await _sut.Handle(query, CancellationToken.None);
ErrorOr<PathExistsResponse> 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<string>(), Arg.Any<bool>());
}
@@ -114,10 +120,11 @@ public class CheckPathExistsQueryHandlerTests
CancellationToken cancellationToken = new(true);
// Act
PathExistsResponse result = await _sut.Handle(query, cancellationToken);
ErrorOr<PathExistsResponse> 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!);
}
}
@@ -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<bool> cancellationRequested = new();
_mockSender.Send(Arg.Any<CheckPathExistsQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => new ValueTask<PathExistsResponse>(Task.Run(async () =>
.Returns(callInfo => new ValueTask<ErrorOr<PathExistsResponse>>(Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return new PathExistsResponse(true);
return ErrorOrFactory.From(new PathExistsResponse(true));
}, callInfo.Arg<CancellationToken>())));
// Act