mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 09:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+243
@@ -0,0 +1,243 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ChangePasswordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChangePasswordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ChangePasswordEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WhenCalledWithValidRequest_ShouldChangePasswordSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: _apiFactory.TestUsername,
|
||||
currentPassword: "TestPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
|
||||
// Assert
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
ChangePasswordResponse? result = JsonSerializer.Deserialize<ChangePasswordResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result!.IsPasswordChanged);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WhenPasswordsDoNotMatch_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: _apiFactory.TestUsername,
|
||||
currentPassword: "OldPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "DifferentPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/change-password", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PasswordsNotMatch", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WhenUserDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: "nonexistentuser",
|
||||
currentPassword: "OldPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("UsernameDoesNotExist", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/change-password", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WhenCurrentPasswordIsIncorrect_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: _apiFactory.TestUsername,
|
||||
currentPassword: "WrongPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("InvalidCurrentPassword", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/change-password", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WhenRequestIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest? request = null;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/change-password", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("UsernameCannotBeEmpty", errors["General.Validation"]);
|
||||
Assert.Contains("CurrentPasswordCannotBeEmpty", errors["General.Validation"]);
|
||||
Assert.Contains("NewPasswordCannotBeEmpty", errors["General.Validation"]);
|
||||
Assert.Contains("NewPasswordConfirmCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: _apiFactory.TestUsername,
|
||||
currentPassword: "OldPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.PostAsJsonAsync("/api/v1/auth/change-password", request, cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _apiFactory.TestUsername!);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Users.Remove(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Users;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUsersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUsersEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUsersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUsersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_WhenCalledWithValidRequest_ShouldReturnUsers()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/users");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
IEnumerable<UserResponse>? result = JsonSerializer.Deserialize<IEnumerable<UserResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotEmpty(result);
|
||||
foreach (UserResponse user in result!)
|
||||
{
|
||||
Assert.NotEqual(Guid.Empty, user.Id);
|
||||
Assert.NotNull(user.Username);
|
||||
Assert.NotEmpty(user.Username);
|
||||
Assert.NotEqual(default, user.CreatedOnUtc);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/users");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/users", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync("/api/v1/auth/users", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Clear junction tables first.
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// Then clear main tables.
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Authentication;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using OtpNet;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="LoginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
private readonly ICryptographyService _cryptographyService;
|
||||
private readonly TotpTokenGenerator _totpTokenGenerator = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly string _testUsername;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public LoginEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||
|
||||
using IServiceScope scope = apiFactory.Services.CreateScope();
|
||||
_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 Login_WhenCalledWithValidCredentials_ShouldLoginSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(user.Username, result!.Username);
|
||||
Assert.False(result.UsesTotp);
|
||||
Assert.NotNull(result.Token);
|
||||
Assert.NotEmpty(result.Token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WhenCalledWithValidCredentialsAndTotp_ShouldLoginSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUserWithTotp();
|
||||
byte[] totpSecret = Convert.FromBase64String(_cryptographyService.Decrypt(user.TotpSecret!));
|
||||
Totp totp = new(totpSecret);
|
||||
string validTotpCode = totp.ComputeTotp(DateTime.UtcNow);
|
||||
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
totpCode: validTotpCode
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(user.Username, result!.Username);
|
||||
Assert.True(result.UsesTotp);
|
||||
Assert.NotNull(result.Token);
|
||||
Assert.NotEmpty(result.Token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WhenCalledWithTempPassword_ShouldLoginSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUserWithTempPassword();
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TempPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(user.Username, result!.Username);
|
||||
Assert.NotNull(result.Token);
|
||||
Assert.NotEmpty(result.Token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WhenCalledWithExpiredTempPassword_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUserWithExpiredTempPassword();
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TempPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("TempPasswordExpired", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/login", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WhenCalledWithInvalidCredentials_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "WrongPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("InvalidUsernameOrPassword", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/login", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WhenCalledWithInvalidTotpCode_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUserWithTotp();
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
totpCode: "000000"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/login", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("InvalidTotpCode", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user without a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUserWithTotp()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
byte[] totpSecret = _totpTokenGenerator.GenerateSecret();
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with a temporary password in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUserWithTempPassword()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
user.TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!"));
|
||||
user.TempPasswordCreated = DateTime.UtcNow;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with an expired temporary password in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUserWithExpiredTempPassword()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
user.TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!"));
|
||||
user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // Expired (> 15 minutes old).
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async 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);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Authentication;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using OtpNet;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RecoverPasswordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new();
|
||||
private readonly ICryptographyService _cryptographyService;
|
||||
private readonly TotpTokenGenerator _totpTokenGenerator = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly string _testUsername;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RecoverPasswordEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||
|
||||
// Get the encryption service with the test key from factory.
|
||||
using IServiceScope scope = apiFactory.Services.CreateScope();
|
||||
_cryptographyService = scope.ServiceProvider.GetRequiredService<ICryptographyService>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = _apiFactory.CreateClient();
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecoverPassword_WhenCalledWithValidRequest_ShouldResetPassword()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateUserWithTotp();
|
||||
|
||||
// Decrypt the TOTP secret and generate a valid code.
|
||||
byte[] totpSecret = Convert.FromBase64String(_cryptographyService.Decrypt(user.TotpSecret!));
|
||||
Totp totp = new(totpSecret);
|
||||
string validTotpCode = totp.ComputeTotp(DateTime.UtcNow);
|
||||
|
||||
RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(
|
||||
username: user.Username,
|
||||
totpCode: validTotpCode
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RecoverPasswordResponse? result = JsonSerializer.Deserialize<RecoverPasswordResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result!.IsPasswordReset);
|
||||
|
||||
// Create a new context to get fresh data.
|
||||
using IServiceScope verificationScope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext verificationContext = verificationScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Ensure we get fresh data from the database.
|
||||
verificationContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
|
||||
UserEntity? updatedUser = await verificationContext.Users
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(u => u.Username == user.Username);
|
||||
|
||||
Assert.NotNull(updatedUser);
|
||||
Assert.NotNull(updatedUser!.TempPassword);
|
||||
Assert.True(Math.Abs((updatedUser.TempPasswordCreated - DateTime.UtcNow)!.Value.TotalSeconds) < 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecoverPassword_WhenUserDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(
|
||||
username: "nonexistentuser",
|
||||
totpCode: "123456"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("UsernameDoesNotExist", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/recover-password", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecoverPassword_WhenInvalidTotpCode_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateUserWithTotp();
|
||||
RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(
|
||||
username: user.Username,
|
||||
totpCode: "000000"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/recover-password", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("InvalidTotpCode", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecoverPassword_WhenRequestIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordRequest? request = null;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/recover-password", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("UsernameCannotBeEmpty", errors["General.Validation"]);
|
||||
Assert.Contains("TotpCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecoverPassword_WhenUserDoesNotUseTotpAndTriesToRecover_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateUserWithoutTotp();
|
||||
|
||||
RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(
|
||||
username: user.Username,
|
||||
totpCode: "123456"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/recover-password", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("InvalidTotpCode", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecoverPassword_WhenUserDoesNotUseTotpAndTriesToRecoverWithoutCode_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
// Setup user without TOTP.
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity userWithoutTotp = _userEntityFixture.Create(username: "userwithoutotp2", password: _hashService.HashString("OldPass123!"));
|
||||
userWithoutTotp.TotpSecret = null; // No TOTP configured.
|
||||
dbContext.Users.Add(userWithoutTotp);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(
|
||||
username: "userwithoutotp2",
|
||||
includeTotpCode: false
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/recover-password", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("TotpCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecoverPassword_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(
|
||||
username: "testuser",
|
||||
totpCode: "123456"
|
||||
);
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request, cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateUserWithTotp()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
byte[] totpSecret = _totpTokenGenerator.GenerateSecret();
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("OldPass123!"));
|
||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user without a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateUserWithoutTotp()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("OldPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async 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);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
+225
@@ -0,0 +1,225 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="RegisterEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegisterEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly RegistrationRequestFixture _registrationRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly string _testUsername;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RegisterEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RegisterEndpointTests(AuthenticatedLuminaApiFactory 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 Register_WhenCalledWithValidRequest_ShouldRegisterUserSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!",
|
||||
use2fa: false
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RegistrationResponse? result = JsonSerializer.Deserialize<RegistrationResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(_testUsername, result!.Username);
|
||||
Assert.NotEqual(Guid.Empty, result.Id);
|
||||
Assert.Null(result.TotpSecret);
|
||||
|
||||
Assert.NotNull(response.Headers.Location);
|
||||
Assert.Equal($"http://localhost/api/v1/users/{result.Id}", response.Headers.Location.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WhenCalledWithValidRequestAnd2FA_ShouldRegisterUserWithTotp()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!",
|
||||
use2fa: true
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RegistrationResponse? result = JsonSerializer.Deserialize<RegistrationResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(_testUsername, result!.Username);
|
||||
Assert.NotEqual(Guid.Empty, result.Id);
|
||||
Assert.NotNull(result.TotpSecret);
|
||||
Assert.NotEmpty(result.TotpSecret);
|
||||
Assert.StartsWith("data:image/png;base64,", result.TotpSecret);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WhenUsernameAlreadyExists_ShouldReturnConflict()
|
||||
{
|
||||
// Arrange
|
||||
await CreateTestUser();
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!",
|
||||
use2fa: false
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status409Conflict, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Conflict", problemDetails["title"].GetString());
|
||||
Assert.Equal("UsernameAlreadyExists", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WhenPasswordsDoNotMatch_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "DifferentPass123!",
|
||||
use2fa: false
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("PasswordsNotMatch", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WhenRequestIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest? request = null;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("UsernameCannotBeEmpty", errors["General.Validation"]);
|
||||
Assert.Contains("PasswordCannotBeEmpty", errors["General.Validation"]);
|
||||
Assert.Contains("PasswordConfirmCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: new PasswordHashService().HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async 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);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Converters;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAuthorizationEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAuthorizationEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions;
|
||||
private HttpClient _client;
|
||||
private readonly string _testUsername;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new();
|
||||
private readonly UserRoleEntityFixture _userRoleEntityFixture = new();
|
||||
private readonly GetAuthorizationRequestFixture _getAuthorizationRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAuthorizationEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAuthorizationEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||
_jsonOptions = new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters =
|
||||
{
|
||||
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase),
|
||||
new ReadOnlySetConverter<AuthorizationPermission>(),
|
||||
new ReadOnlySetConverter<string>()
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorization_WhenCalledWithValidRequest_ShouldReturnAuthorizationDetails()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = await dbContext.Users
|
||||
.Include(user => user.UserRole)
|
||||
.ThenInclude(userRole => userRole.Role)
|
||||
.Include(user => user.UserPermissions)
|
||||
.ThenInclude(userPermission => userPermission.Permission)
|
||||
.FirstAsync(user => user.Username == _apiFactory.TestUsername);
|
||||
await AddRolesAndPermissionsToUser(user, dbContext);
|
||||
GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId: user.Id);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AuthorizationResponse? result = JsonSerializer.Deserialize<AuthorizationResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(user.Id, result!.UserId);
|
||||
Assert.Contains("Admin", result.Role);
|
||||
Assert.Contains(AuthorizationPermission.CanViewUsers, result.Permissions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorization_WhenUserDoesNotExist_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId: Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/get-authorization", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorization_WhenUserIdIsEmpty_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/auth/get-authorization", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains("UserIdCannotBeEmpty", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorization_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId: Guid.NewGuid());
|
||||
CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
private async Task<UserEntity> AddRolesAndPermissionsToUser(UserEntity existingUser, LuminaDbContext dbContext)
|
||||
{
|
||||
// Create and save role and permission first.
|
||||
RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin");
|
||||
PermissionEntity viewUsersPermission = _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers);
|
||||
|
||||
await dbContext.Roles.AddAsync(adminRole);
|
||||
await dbContext.Permissions.AddAsync(viewUsersPermission);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Create role permission.
|
||||
RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create(role: adminRole, permission: viewUsersPermission);
|
||||
await dbContext.RolePermissions.AddAsync(rolePermission);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Remove existing user role if any.
|
||||
if (existingUser.UserRole != null)
|
||||
dbContext.UserRoles.Remove(existingUser.UserRole);
|
||||
|
||||
// Add new user role.
|
||||
UserRoleEntity userRole = _userRoleEntityFixture.Create(user: existingUser, role: adminRole);
|
||||
await dbContext.UserRoles.AddAsync(userRole);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Refresh the user entity.
|
||||
await dbContext.Entry(existingUser).ReloadAsync();
|
||||
|
||||
return existingUser;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async 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);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserPermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserPermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserPermissionsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserPermissions_WhenCalledWithValidRequest_ShouldReturnUserPermissions()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
Assert.NotNull(user);
|
||||
|
||||
// Add a direct user permission.
|
||||
PermissionEntity permission = dbContext.Permissions.First();
|
||||
UserPermissionEntity userPermission = _userPermissionEntityFixture.Create(user, permission);
|
||||
dbContext.UserPermissions.Add(userPermission);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user.Id}/permissions");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
IEnumerable<PermissionResponse>? result = JsonSerializer.Deserialize<IEnumerable<PermissionResponse>>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotEmpty(result);
|
||||
foreach (PermissionResponse perm in result!)
|
||||
{
|
||||
Assert.NotEqual(Guid.Empty, perm.Id);
|
||||
Assert.NotEqual(AuthorizationPermission.None, perm.PermissionName);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserPermissions_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
Assert.NotNull(user);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/permissions");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/auth/users/{user!.Id}/permissions", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserPermissions_WhenUserDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentUserId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{nonExistentUserId}/permissions");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("UsernameDoesNotExist", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/auth/users/{nonExistentUserId}/permissions", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserPermissions_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
Assert.NotNull(user);
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/permissions", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Clear junction tables first.
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// Then clear main tables.
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserRoleEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserRoleEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRole_WhenCalledWithValidRequest_ShouldReturnUserRole()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
Assert.NotNull(user);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/role");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
RoleResponse? result = JsonSerializer.Deserialize<RoleResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotEqual(Guid.Empty, result!.Id);
|
||||
Assert.Equal("Admin", result.RoleName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRole_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
Assert.NotNull(user);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/role");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/auth/users/{user!.Id}/role", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRole_WhenUserDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentUserId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/users/{nonExistentUserId}/role");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("UsernameDoesNotExist", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/auth/users/{nonExistentUserId}/role", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRole_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault();
|
||||
Assert.NotNull(user);
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/auth/users/{user!.Id}/role", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Clear junction tables first.
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// Then clear main tables.
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateUserRoleAndPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserRoleAndPermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateUserRoleAndPermissionsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenCalledWithValidRequest_ShouldUpdateUserRoleAndPermissions()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Create a non-admin role first.
|
||||
RoleEntity editorRole = _roleEntityFixture.Create(roleName: "Editor");
|
||||
dbContext.Roles.Add(editorRole);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Create test user.
|
||||
UserEntity user = _userEntityFixture.Create(username: "TestUser", password: "HashedPassword");
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)];
|
||||
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: user.Id,
|
||||
roleId: editorRole.Id,
|
||||
permissions: permissions.Select(p => p.Id).ToList()
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{user.Id}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
JsonNode? jsonNode = JsonNode.Parse(content);
|
||||
|
||||
Assert.NotNull(jsonNode);
|
||||
Assert.Equal(user.Id, Guid.Parse(jsonNode!["userId"]!.ToString()));
|
||||
Assert.Equal("Editor", jsonNode["role"]!.ToString());
|
||||
Assert.True(jsonNode["permissions"]!.AsArray().Count > 0);
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
roleId: Guid.NewGuid(),
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{request.UserId}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/auth/users/{request.UserId}/role-and-permissions", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenTryingToRemoveLastAdmin_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Create Editor role.
|
||||
RoleEntity editorRole = _roleEntityFixture.Create(roleName: "Editor");
|
||||
dbContext.Roles.Add(editorRole);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Get the admin user that was created by CreateAuthenticatedAdminClientAsync.
|
||||
UserEntity? adminUser = dbContext.Users.FirstOrDefault(u => u.UserRole!.Role.RoleName == "Admin");
|
||||
Assert.NotNull(adminUser);
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: adminUser!.Id,
|
||||
roleId: editorRole.Id,
|
||||
permissions: []
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{request.UserId}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Forbidden", problemDetails["title"].GetString());
|
||||
Assert.Equal("CannotRemoveLastAdmin", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/auth/users/{request.UserId}/role-and-permissions", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenUserDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid nonExistentUserId = Guid.NewGuid();
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: nonExistentUserId,
|
||||
roleId: Guid.NewGuid(),
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/auth/users/{nonExistentUserId}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("UserDoesNotExist", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/auth/users/{nonExistentUserId}/role-and-permissions", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenCancellationRequested_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cts = new();
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
roleId: Guid.NewGuid(),
|
||||
permissions: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.PutAsJsonAsync($"/api/v1/auth/users/{request.UserId}/role-and-permissions", request, cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Clear junction tables first.
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
// Then clear main tables.
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetPlaybackState;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Settings.GetPlaybackState;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetPlaybackStateEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackStateEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackStateEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPlaybackStateEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackState_WhenNoSettingsAreStored_ShouldReturnTheDefaultPlaybackState()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(1.0, result!.Volume);
|
||||
Assert.False(result.IsMuted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackState_WhenSettingsAreStored_ShouldReturnTheStoredPlaybackState()
|
||||
{
|
||||
// Arrange
|
||||
await CreateTestUserSettings(volume: 0.42, isMuted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(0.42, result!.Volume);
|
||||
Assert.True(result.IsMuted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackState_WhenSettingsBelongToAnotherUser_ShouldReturnTheDefaultPlaybackState()
|
||||
{
|
||||
// Arrange
|
||||
await CreateSettingsForAnotherUserAsync(volume: 0.1, isMuted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(1.0, result!.Volume);
|
||||
Assert.False(result.IsMuted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackState_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/users/me/settings/playback-state");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the playback state of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <param name="volume">The volume to store.</param>
|
||||
/// <param name="isMuted">The mute state to store.</param>
|
||||
/// <returns>The stored settings.</returns>
|
||||
private async Task<UserSettingsEntity> CreateTestUserSettings(double volume, bool isMuted)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id;
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: userId, volume: volume, isMuted: isMuted);
|
||||
|
||||
dbContext.UserSettings.Add(settings);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return settings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds another user and stores that user's playback state, keeping it out of the current user's scope.
|
||||
/// </summary>
|
||||
/// <param name="volume">The volume to store.</param>
|
||||
/// <param name="isMuted">The mute state to store.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task CreateSettingsForAnotherUserAsync(double volume, bool isMuted)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity otherUser = _userEntityFixture.Create(username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!");
|
||||
otherUser.TotpSecret = null;
|
||||
dbContext.Users.Add(otherUser);
|
||||
dbContext.UserSettings.Add(_userSettingsEntityFixture.Create(userId: otherUser.Id, volume: volume, isMuted: isMuted));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
await dbContext.Set<UserSettingsEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Settings.GetUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserSettings_WhenSettingsExist_ShouldReturnStoredSettings()
|
||||
{
|
||||
// Arrange
|
||||
UserSettingsEntity storedSettings = await CreateTestUserSettings();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
UserSettingsResponse? result = JsonSerializer.Deserialize<UserSettingsResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(storedSettings.UserId, result!.UserId);
|
||||
Assert.Equal(storedSettings.IsPaginationEnabled, result.IsPaginationEnabled);
|
||||
Assert.Equal(storedSettings.ItemsPerPage, result.ItemsPerPage);
|
||||
Assert.Equal(storedSettings.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(VuMeterOrientation.Horizontal, result.VuMeterOrientation);
|
||||
Assert.Equal(20, result.VuMeterSegmentCount);
|
||||
Assert.Equal(4, result.VuMeterSegmentGap);
|
||||
Assert.Equal(0.35, result.VuMeterMediumThreshold);
|
||||
Assert.Equal(0.9, result.VuMeterHighThreshold);
|
||||
Assert.False(result.VuMeterShowPeak);
|
||||
Assert.Equal(1200, result.VuMeterPeakHoldDurationInMilliseconds);
|
||||
Assert.Equal(7.5, result.VuMeterReleasePerSecond);
|
||||
Assert.Equal(0.25, result.VuMeterPeakReleasePerSecond);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserSettings_WhenSettingsDoNotExist_ShouldReturnDefaultSettings()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
UserSettingsResponse? result = JsonSerializer.Deserialize<UserSettingsResponse>(content, _jsonOptions);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result!.IsPaginationEnabled);
|
||||
Assert.Equal(48, result.ItemsPerPage);
|
||||
Assert.False(result.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(VuMeterOrientation.Vertical, result.VuMeterOrientation);
|
||||
Assert.Equal(12, result.VuMeterSegmentCount);
|
||||
Assert.Equal(1, result.VuMeterSegmentGap);
|
||||
Assert.Equal(0.6, result.VuMeterMediumThreshold);
|
||||
Assert.Equal(0.8, result.VuMeterHighThreshold);
|
||||
Assert.True(result.VuMeterShowPeak);
|
||||
Assert.Equal(650, result.VuMeterPeakHoldDurationInMilliseconds);
|
||||
Assert.Equal(3.0, result.VuMeterReleasePerSecond);
|
||||
Assert.Equal(0.65, result.VuMeterPeakReleasePerSecond);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/users/me/settings");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
private async Task<UserSettingsEntity> CreateTestUserSettings()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id;
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create(
|
||||
userId: userId,
|
||||
isPaginationEnabled: false,
|
||||
itemsPerPage: 24,
|
||||
shouldIgnoreThePrefixForAlphaPicker: true,
|
||||
vuMeterOrientation: VuMeterOrientation.Horizontal,
|
||||
vuMeterSegmentCount: 20,
|
||||
vuMeterSegmentGap: 4,
|
||||
vuMeterMediumThreshold: 0.35,
|
||||
vuMeterHighThreshold: 0.9,
|
||||
vuMeterShowPeak: false,
|
||||
vuMeterPeakHoldDurationInMilliseconds: 1200,
|
||||
vuMeterReleasePerSecond: 7.5,
|
||||
vuMeterPeakReleasePerSecond: 0.25);
|
||||
|
||||
dbContext.UserSettings.Add(settings);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return settings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
await dbContext.Set<UserSettingsEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdatePlaybackStateEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePlaybackStateEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UpdatePlaybackStateRequestFixture _updatePlaybackStateRequestFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePlaybackStateEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdatePlaybackStateEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenCalledWithValidRequest_ShouldStoreTheReportedStateWithTheDefaultHandEditedSettings()
|
||||
{
|
||||
// Arrange
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
UserSettingsEntity? storedSettings = await GetCurrentUserSettingsAsync();
|
||||
Assert.NotNull(storedSettings);
|
||||
Assert.Equal(0.35, storedSettings!.Volume);
|
||||
Assert.True(storedSettings.IsMuted);
|
||||
Assert.True(storedSettings.IsPaginationEnabled);
|
||||
Assert.Equal(48, storedSettings.ItemsPerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenSettingsAlreadyExist_ShouldPreserveTheHandEditedSettings()
|
||||
{
|
||||
// Arrange
|
||||
await CreateTestUserSettingsAsync(volume: 1.0, isMuted: false, itemsPerPage: 24, isPaginationEnabled: false);
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.25, isMuted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
UserSettingsEntity? storedSettings = await GetCurrentUserSettingsAsync();
|
||||
Assert.NotNull(storedSettings);
|
||||
Assert.Equal(0.25, storedSettings!.Volume);
|
||||
Assert.True(storedSettings.IsMuted);
|
||||
Assert.False(storedSettings.IsPaginationEnabled);
|
||||
Assert.Equal(24, storedSettings.ItemsPerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenUpdatedThenRead_ShouldReturnTheReportedState()
|
||||
{
|
||||
// Arrange
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.6, isMuted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage updateResponse = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
HttpResponseMessage getResponse = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
|
||||
|
||||
// Assert
|
||||
updateResponse.EnsureSuccessStatusCode();
|
||||
getResponse.EnsureSuccessStatusCode();
|
||||
string content = await getResponse.Content.ReadAsStringAsync();
|
||||
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(0.6, result!.Volume);
|
||||
Assert.True(result.IsMuted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenCalledByOneUser_ShouldNotChangeThePlaybackStateOfAnotherUser()
|
||||
{
|
||||
// Arrange
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.25, isMuted: true);
|
||||
HttpResponseMessage updateResponse = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
HttpClient otherClient = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage getResponse = await otherClient.GetAsync("/api/v1/users/me/settings/playback-state");
|
||||
|
||||
// Assert
|
||||
updateResponse.EnsureSuccessStatusCode();
|
||||
getResponse.EnsureSuccessStatusCode();
|
||||
string content = await getResponse.Content.ReadAsStringAsync();
|
||||
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(1.0, result!.Volume);
|
||||
Assert.False(result.IsMuted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenVolumeIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(includeVolume: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VolumeCannotBeNull");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-0.01)] // Just below the minimum.
|
||||
[InlineData(1.01)] // Just above the maximum.
|
||||
public async Task UpdatePlaybackState_WhenVolumeIsOutOfRange_ShouldReturnValidationError(double volume)
|
||||
{
|
||||
// Arrange
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: volume);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VolumeMustBeBetweenZeroAndOne");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenIsMutedIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(includeIsMuted: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "IsMutedCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenPayloadHasUnknownFields_ShouldIgnoreThemAndStoreTheReportedState()
|
||||
{
|
||||
// Arrange
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.15, isMuted: false);
|
||||
JsonObject payload = JsonSerializer.SerializeToNode(request, new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject();
|
||||
payload["unknownField"] = "ignored";
|
||||
StringContent requestContent = new(payload.ToJsonString(), Encoding.UTF8, "application/json");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync("/api/v1/users/me/settings/playback-state", requestContent);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
UserSettingsEntity? storedSettings = await GetCurrentUserSettingsAsync();
|
||||
Assert.NotNull(storedSettings);
|
||||
Assert.Equal(0.15, storedSettings!.Volume);
|
||||
Assert.False(storedSettings.IsMuted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that <paramref name="response"/> is a validation problem response carrying the specified error.
|
||||
/// </summary>
|
||||
/// <param name="response">The response to assert.</param>
|
||||
/// <param name="expectedError">The exact error description expected in the validation errors.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task AssertValidationErrorAsync(HttpResponseMessage response, string expectedError)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/users/me/settings/playback-state", problemDetails["instance"].GetString());
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains(expectedError, errors["General.Validation"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores a playback state for the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <param name="volume">The volume to store.</param>
|
||||
/// <param name="isMuted">The mute state to store.</param>
|
||||
/// <param name="itemsPerPage">The number of items displayed per page to store.</param>
|
||||
/// <param name="isPaginationEnabled">Whether pagination is enabled.</param>
|
||||
/// <returns>The stored settings.</returns>
|
||||
private async Task<UserSettingsEntity> CreateTestUserSettingsAsync(double volume, bool isMuted, int itemsPerPage, bool isPaginationEnabled)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id;
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create(
|
||||
userId: userId,
|
||||
volume: volume,
|
||||
isMuted: isMuted,
|
||||
itemsPerPage: itemsPerPage,
|
||||
isPaginationEnabled: isPaginationEnabled);
|
||||
|
||||
dbContext.UserSettings.Add(settings);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return settings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the stored playback state of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The stored settings, or <see langword="null"/> when the user has none.</returns>
|
||||
private async Task<UserSettingsEntity?> GetCurrentUserSettingsAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id;
|
||||
return await dbContext.UserSettings.FirstOrDefaultAsync(settings => settings.UserId == userId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
await dbContext.Set<UserSettingsEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+503
@@ -0,0 +1,503 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="UpdateUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateUserSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenCalledWithValidRequest_ShouldUpdateSettings()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: false,
|
||||
itemsPerPage: 24,
|
||||
shouldIgnoreThePrefixForAlphaPicker: true,
|
||||
isThemeCachingEnabled: false,
|
||||
shouldAggregateMetadataWhenMissing: false,
|
||||
vuMeterOrientation: VuMeterOrientation.Horizontal,
|
||||
vuMeterSegmentCount: 20,
|
||||
vuMeterSegmentGap: 4,
|
||||
vuMeterMediumThreshold: 0.35,
|
||||
vuMeterHighThreshold: 0.9,
|
||||
vuMeterShowPeak: false,
|
||||
vuMeterPeakHoldDurationInMilliseconds: 1200,
|
||||
vuMeterReleasePerSecond: 7.5,
|
||||
vuMeterPeakReleasePerSecond: 0.25
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id;
|
||||
UserSettingsEntity? storedSettings = await dbContext.UserSettings.FirstOrDefaultAsync(settings => settings.UserId == userId);
|
||||
Assert.NotNull(storedSettings);
|
||||
Assert.False(storedSettings.IsPaginationEnabled);
|
||||
Assert.Equal(24, storedSettings.ItemsPerPage);
|
||||
Assert.True(storedSettings.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.False(storedSettings.IsThemeCachingEnabled);
|
||||
Assert.Equal(VuMeterOrientation.Horizontal, storedSettings.VuMeterOrientation);
|
||||
Assert.Equal(20, storedSettings.VuMeterSegmentCount);
|
||||
Assert.Equal(4, storedSettings.VuMeterSegmentGap);
|
||||
Assert.Equal(0.35, storedSettings.VuMeterMediumThreshold);
|
||||
Assert.Equal(0.9, storedSettings.VuMeterHighThreshold);
|
||||
Assert.False(storedSettings.VuMeterShowPeak);
|
||||
Assert.Equal(1200, storedSettings.VuMeterPeakHoldDurationInMilliseconds);
|
||||
Assert.Equal(7.5, storedSettings.VuMeterReleasePerSecond);
|
||||
Assert.Equal(0.25, storedSettings.VuMeterPeakReleasePerSecond);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenItemsPerPageIsNotPositive_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: 0,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "ItemsPerPageMustBeGreaterThanZero");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: 48,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterOrientationIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterOrientation: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterOrientationCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterSegmentCountIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterSegmentCount: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterSegmentCountCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterSegmentGapIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterSegmentGap: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterSegmentGapCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterMediumThresholdIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterMediumThreshold: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterMediumThresholdCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterHighThreshold: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterHighThresholdCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterShowPeakIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterShowPeak: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterShowPeakCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterPeakHoldDurationIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterPeakHoldDurationInMilliseconds: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterPeakHoldDurationCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterReleasePerSecondIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterReleasePerSecond: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterReleasePerSecondCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterPeakReleasePerSecondIsNull_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(includeVuMeterPeakReleasePerSecond: false);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterPeakReleasePerSecondCannotBeNull");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterOrientationIsNotDefined_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterOrientation: (VuMeterOrientation)999);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "InvalidVuMeterOrientation");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)] // Below the minimum.
|
||||
[InlineData(129)] // Above the maximum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterSegmentCountIsOutOfRange_ShouldReturnValidationError(int vuMeterSegmentCount)
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterSegmentCount: vuMeterSegmentCount);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterSegmentCountMustBeBetweenOneAndOneHundredTwentyEight");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1)] // Below the minimum.
|
||||
[InlineData(33)] // Above the maximum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterSegmentGapIsOutOfRange_ShouldReturnValidationError(int vuMeterSegmentGap)
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterSegmentGap: vuMeterSegmentGap);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterSegmentGapMustBeBetweenZeroAndThirtyTwo");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-0.01)] // Just below the minimum.
|
||||
[InlineData(1.01)] // Just above the maximum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterMediumThresholdIsOutOfRange_ShouldReturnValidationError(double vuMeterMediumThreshold)
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
vuMeterMediumThreshold: vuMeterMediumThreshold,
|
||||
vuMeterHighThreshold: 1.0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterMediumThresholdMustBeBetweenZeroAndOne");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-0.01)] // Just below the minimum.
|
||||
[InlineData(1.01)] // Just above the maximum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsOutOfRange_ShouldReturnValidationError(double vuMeterHighThreshold)
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
vuMeterMediumThreshold: 0.0,
|
||||
vuMeterHighThreshold: vuMeterHighThreshold);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterHighThresholdMustBeBetweenZeroAndOne");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsLowerThanMediumThreshold_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
vuMeterMediumThreshold: 0.9,
|
||||
vuMeterHighThreshold: 0.1);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterHighThresholdMustBeGreaterThanOrEqualToMediumThreshold");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.5, 0.5)] // The thresholds are equal.
|
||||
[InlineData(0.4, 0.9)] // The high threshold is greater than the medium one.
|
||||
public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsGreaterThanOrEqualToMediumThreshold_ShouldUpdateSettings(
|
||||
double vuMeterMediumThreshold,
|
||||
double vuMeterHighThreshold)
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
vuMeterMediumThreshold: vuMeterMediumThreshold,
|
||||
vuMeterHighThreshold: vuMeterHighThreshold);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1)] // Below the minimum.
|
||||
[InlineData(10001)] // Above the maximum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterPeakHoldDurationIsOutOfRange_ShouldReturnValidationError(int vuMeterPeakHoldDurationInMilliseconds)
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
vuMeterPeakHoldDurationInMilliseconds: vuMeterPeakHoldDurationInMilliseconds);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterPeakHoldDurationMustBeBetweenZeroAndTenThousandMilliseconds");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-0.01)] // Just below the minimum.
|
||||
[InlineData(100.01)] // Just above the maximum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterReleasePerSecondIsOutOfRange_ShouldReturnValidationError(double vuMeterReleasePerSecond)
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterReleasePerSecond: vuMeterReleasePerSecond);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterReleasePerSecondMustBeBetweenZeroAndOneHundred");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-0.01)] // Just below the minimum.
|
||||
[InlineData(100.01)] // Just above the maximum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterPeakReleasePerSecondIsOutOfRange_ShouldReturnValidationError(double vuMeterPeakReleasePerSecond)
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterPeakReleasePerSecond: vuMeterPeakReleasePerSecond);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
await AssertValidationErrorAsync(response, "VuMeterPeakReleasePerSecondMustBeBetweenZeroAndOneHundred");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenAllVuMeterValuesAreAtTheirMinimums_ShouldUpdateSettings()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
vuMeterOrientation: VuMeterOrientation.Vertical,
|
||||
vuMeterSegmentCount: 1,
|
||||
vuMeterSegmentGap: 0,
|
||||
vuMeterMediumThreshold: 0.0,
|
||||
vuMeterHighThreshold: 0.0,
|
||||
vuMeterShowPeak: false,
|
||||
vuMeterPeakHoldDurationInMilliseconds: 0,
|
||||
vuMeterReleasePerSecond: 0.0,
|
||||
vuMeterPeakReleasePerSecond: 0.0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenAllVuMeterValuesAreAtTheirMaximums_ShouldUpdateSettings()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
vuMeterOrientation: VuMeterOrientation.Horizontal,
|
||||
vuMeterSegmentCount: 128,
|
||||
vuMeterSegmentGap: 32,
|
||||
vuMeterMediumThreshold: 1.0,
|
||||
vuMeterHighThreshold: 1.0,
|
||||
vuMeterShowPeak: true,
|
||||
vuMeterPeakHoldDurationInMilliseconds: 10000,
|
||||
vuMeterReleasePerSecond: 100.0,
|
||||
vuMeterPeakReleasePerSecond: 100.0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that <paramref name="response"/> is a validation problem response carrying the specified error.
|
||||
/// </summary>
|
||||
/// <param name="response">The response to assert.</param>
|
||||
/// <param name="expectedError">The exact error description expected in the validation errors.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task AssertValidationErrorAsync(HttpResponseMessage response, string expectedError)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/users/me/settings", problemDetails["instance"].GetString());
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.Contains(expectedError, errors["General.Validation"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
await dbContext.Set<UserSettingsEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user