Adds user settings management

Adds the UserSettings aggregate with pagination and alpha picker preferences, keyed to a user with a dedicated UserId foreign key. Adds GET and PUT /users/me/settings API endpoints, a localized Tools > Settings page with save confirmation, the EF migration for the UserSettings table, and unit, integration and security tests.
This commit is contained in:
BinaryAlley committed 2026-08-16 08:37:33 -07:00
1 parent c3f8786fe4
commit 2354e21d42
65 files changed
+4711 -21

No files matched your search

@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
/// <summary>
/// Fixture class for the <see cref="UserSettingsEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserSettingsEntityFixture
{
/// <summary>
/// Creates a random valid <see cref="UserSettingsEntity"/>.
/// </summary>
/// <param name="id">Optional. The Id of the user settings.</param>
/// <param name="userId">Optional. The Id of the user that owns these settings.</param>
/// <param name="isPaginationEnabled">Optional. Whether pagination is enabled for the user, or not.</param>
/// <param name="itemsPerPage">Optional. The number of library items displayed per page when pagination is enabled.</param>
/// <param name="ignoreThePrefixForAlphaPicker">Optional. Whether the "The" prefix is ignored by the alpha picker, or not.</param>
/// <returns>The created user settings entity.</returns>
public UserSettingsEntity Create(
Guid? id = null,
Guid? userId = null,
bool? isPaginationEnabled = null,
int? itemsPerPage = null,
bool? ignoreThePrefixForAlphaPicker = null)
{
return new Faker<UserSettingsEntity>()
.CustomInstantiator(f => new UserSettingsEntity
{
Id = id ?? Guid.NewGuid(),
UserId = userId ?? Guid.NewGuid(),
IsPaginationEnabled = isPaginationEnabled ?? f.Random.Bool(),
ItemsPerPage = itemsPerPage ?? f.Random.Int(1, 100),
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? f.Random.Bool()
})
.Generate();
}
/// <summary>
/// Creates a list of <see cref="UserSettingsEntity"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UserSettingsEntity"/> instances.</returns>
public List<UserSettingsEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
/// <summary>
/// Fixture class for the <see cref="UpdateUserSettingsCommand"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateUserSettingsCommandFixture
{
/// <summary>
/// Creates a random valid command to update the settings of the current user.
/// </summary>
/// <param name="isPaginationEnabled">Optional. Whether pagination is enabled for the user, or not.</param>
/// <param name="itemsPerPage">Optional. The number of library items displayed per page when pagination is enabled.</param>
/// <param name="ignoreThePrefixForAlphaPicker">Optional. Whether the "The" prefix is ignored by the alpha picker, or not.</param>
/// <returns>The created command.</returns>
public UpdateUserSettingsCommand Create(
bool? isPaginationEnabled = null,
int? itemsPerPage = null,
bool? ignoreThePrefixForAlphaPicker = null)
{
return new Faker<UpdateUserSettingsCommand>()
.CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default))
.RuleFor(x => x.IsPaginationEnabled, f => isPaginationEnabled ?? f.Random.Bool())
.RuleFor(x => x.ItemsPerPage, f => itemsPerPage ?? f.Random.Int(1, 100))
.RuleFor(x => x.IgnoreThePrefixForAlphaPicker, f => ignoreThePrefixForAlphaPicker ?? f.Random.Bool())
.Generate();
}
/// <summary>
/// Creates a list of <see cref="UpdateUserSettingsCommand"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<UpdateUserSettingsCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,141 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.UsersManagement.Settings;
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.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 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.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker);
}
[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.IgnoreThePrefixForAlphaPicker);
}
[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 = new()
{
Id = Guid.NewGuid(),
UserId = userId,
IsPaginationEnabled = false,
ItemsPerPage = 24,
IgnoreThePrefixForAlphaPicker = true
};
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();
}
}
@@ -0,0 +1,143 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.UsersManagement.Settings;
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.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 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 = new(
IsPaginationEnabled: false,
ItemsPerPage: 24,
IgnoreThePrefixForAlphaPicker: true
);
// 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.IgnoreThePrefixForAlphaPicker);
}
[Fact]
public async Task UpdateUserSettings_WhenItemsPerPageIsNotPositive_ShouldReturnValidationError()
{
// Arrange
UpdateUserSettingsRequest request = new(
IsPaginationEnabled: true,
ItemsPerPage: 0,
IgnoreThePrefixForAlphaPicker: false
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", 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/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("ItemsPerPageMustBeGreaterThanZero", errors["General.Validation"]);
}
[Fact]
public async Task UpdateUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
UpdateUserSettingsRequest request = new(
IsPaginationEnabled: true,
ItemsPerPage: 48,
IgnoreThePrefixForAlphaPicker: false
);
// Act
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <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();
}
}
@@ -0,0 +1,116 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.GetUserSettings;
/// <summary>
/// Contains security tests for the <c>/users/me/settings</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly PasswordHashService _hashService = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUserSettingsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, 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.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/users/me/settings", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Fact]
public async Task GetUserSettings_WhenAuthenticated_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync("/api/v1/users/me/settings");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"testuser_{Guid.NewGuid()}";
dbContext.Users.Add(new UserEntity
{
Id = userId,
Username = username,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
UserPermissions = [],
UserRole = null,
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow
});
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
}
}
@@ -0,0 +1,150 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Requests.UsersManagement.Settings;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings;
/// <summary>
/// Contains security tests for the <c>/users/me/settings</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly PasswordHashService _hashService = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateUserSettingsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task UpdateUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
UpdateUserSettingsRequest request = new(
IsPaginationEnabled: true,
ItemsPerPage: 48,
IgnoreThePrefixForAlphaPicker: false
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, 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.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/users/me/settings", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Fact]
public async Task UpdateUserSettings_WhenItemsPerPageIsAtIntMaxValue_ShouldNotCrash()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await CreateAndAuthenticateUserAsync(client);
UpdateUserSettingsRequest request = new(
IsPaginationEnabled: true,
ItemsPerPage: int.MaxValue,
IgnoreThePrefixForAlphaPicker: false
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task UpdateUserSettings_WhenItemsPerPageIsAtIntMinValue_ShouldReturnValidationErrorWithoutCrashing()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await CreateAndAuthenticateUserAsync(client);
UpdateUserSettingsRequest request = new(
IsPaginationEnabled: true,
ItemsPerPage: int.MinValue,
IgnoreThePrefixForAlphaPicker: false
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"testuser_{Guid.NewGuid()}";
dbContext.Users.Add(new UserEntity
{
Id = userId,
Username = username,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
UserPermissions = [],
UserRole = null,
CreatedBy = userId,
CreatedOnUtc = DateTime.UtcNow
});
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
}
}
@@ -0,0 +1,169 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
/// <summary>
/// Contains unit tests for the <see cref="UpdateUserSettingsCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateUserSettingsCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly IValidator<UpdateUserSettingsCommand> _mockValidator;
private readonly UpdateUserSettingsCommandHandler _sut;
private readonly UpdateUserSettingsCommandFixture _updateUserSettingsCommandFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateUserSettingsCommandHandlerTests"/> class.
/// </summary>
public UpdateUserSettingsCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockValidator = Substitute.For<IValidator<UpdateUserSettingsCommand>>();
_mockValidator.Validate(Arg.Any<UpdateUserSettingsCommand>())
.Returns([]);
_sut = new UpdateUserSettingsCommandHandler(_mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenSettingsDoNotExist_ShouldInsertSettingsAndReturnUpdated()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(null));
_mockUserSettingsRepository.InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await _mockUserSettingsRepository.Received(1).InsertAsync(
Arg.Is<UserSettingsEntity>(settings =>
settings.UserId == _userId &&
settings.IsPaginationEnabled == command.IsPaginationEnabled &&
settings.ItemsPerPage == command.ItemsPerPage &&
settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker),
Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSettingsExist_ShouldUpdateSettingsAndReturnUpdated()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(existingSettings));
_mockUserSettingsRepository.UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await _mockUserSettingsRepository.Received(1).UpdateAsync(
Arg.Is<UserSettingsEntity>(settings =>
settings.UserId == _userId &&
settings.IsPaginationEnabled == command.IsPaginationEnabled &&
settings.ItemsPerPage == command.ItemsPerPage &&
settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker),
Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
_mockValidator.Validate(Arg.Any<UpdateUserSettingsCommand>())
.Returns([DomainErrors.UserSettings.ItemsPerPageMustBeGreaterThanZero]);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError);
await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotPersist()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByUserIdReturnsError_ShouldReturnError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to retrieve user settings");
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
/// <summary>
/// Contains unit tests for the <see cref="UpdateUserSettingsCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateUserSettingsCommandValidatorTests
{
private readonly UpdateUserSettingsCommandValidator _validator = new();
private readonly UpdateUserSettingsCommandFixture _updateUserSettingsCommandFixture = new();
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(-100)]
public void Validate_WhenItemsPerPageIsNotPositive_ShouldHaveValidationError(int itemsPerPage)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(itemsPerPage: itemsPerPage);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero);
}
[Theory]
[InlineData(1)]
[InlineData(48)]
[InlineData(1000000)]
public void Validate_WhenItemsPerPageIsPositive_ShouldNotHaveValidationError(int itemsPerPage)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(itemsPerPage: itemsPerPage);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,119 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.UsersManagement.Settings;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Queries.GetUserSettings;
/// <summary>
/// Contains unit tests for the <see cref="GetUserSettingsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserSettingsQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly GetUserSettingsQueryHandler _sut;
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="GetUserSettingsQueryHandlerTests"/> class.
/// </summary>
public GetUserSettingsQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_sut = new GetUserSettingsQueryHandler(_mockCurrentUserService, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenSettingsExist_ShouldReturnStoredSettings()
{
// Arrange
GetUserSettingsQuery query = new();
UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: _userId);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(storedSettings));
// Act
Result<UserSettingsResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(storedSettings.UserId, result.Value.UserId);
Assert.Equal(storedSettings.IsPaginationEnabled, result.Value.IsPaginationEnabled);
Assert.Equal(storedSettings.ItemsPerPage, result.Value.ItemsPerPage);
Assert.Equal(storedSettings.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker);
}
[Fact]
public async Task HandleAsync_WhenSettingsDoNotExist_ShouldReturnDefaultSettings()
{
// Arrange
GetUserSettingsQuery query = new();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(null));
// Act
Result<UserSettingsResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(_userId, result.Value.UserId);
Assert.True(result.Value.IsPaginationEnabled);
Assert.Equal(48, result.Value.ItemsPerPage);
Assert.False(result.Value.IgnoreThePrefixForAlphaPicker);
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
GetUserSettingsQuery query = new();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<UserSettingsResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByIdReturnsError_ShouldReturnError()
{
// Arrange
GetUserSettingsQuery query = new();
Error error = Error.Failure("Database.Error", "Failed to retrieve user settings");
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<UserSettingsResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,179 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.Repositories.Users;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Users;
/// <summary>
/// Contains unit tests for the <see cref="UserSettingsRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserSettingsRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly UserSettingsRepository _sut;
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UserSettingsRepositoryTests"/> class.
/// </summary>
public UserSettingsRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new UserSettingsRepository(_mockContext);
}
[Fact]
public async Task InsertAsync_WhenSettingsDoNotExist_ShouldAddSettingsToContextAndReturnCreated()
{
// Arrange
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
// Act
Result<Created> result = await _sut.InsertAsync(settings, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
EntityEntry<UserSettingsEntity>? addedSettings = _mockContext.ChangeTracker.Entries<UserSettingsEntity>()
.FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == settings.Id);
Assert.NotNull(addedSettings);
Assert.Equal(settings.UserId, addedSettings.Entity.UserId);
}
[Fact]
public async Task InsertAsync_WhenSettingsForUserAlreadyExist_ShouldReturnError()
{
// Arrange
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
_mockContext.UserSettings.Add(settings);
await _mockContext.SaveChangesAsync();
// Act
Result<Created> result = await _sut.InsertAsync(settings, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.UserSettings.UserSettingsAlreadyExists, result.FirstError);
Assert.Single(_mockContext.ChangeTracker.Entries<UserSettingsEntity>());
}
[Fact]
public async Task GetByIdAsync_WhenSettingsExist_ShouldReturnSettings()
{
// Arrange
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
_mockContext.UserSettings.Add(settings);
await _mockContext.SaveChangesAsync();
// Act
Result<UserSettingsEntity?> result = await _sut.GetByIdAsync(settings.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(settings.Id, result.Value.Id);
Assert.Equal(settings.UserId, result.Value.UserId);
}
[Fact]
public async Task GetByIdAsync_WhenSettingsDoNotExist_ShouldReturnNull()
{
// Act
Result<UserSettingsEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByUserIdAsync_WhenSettingsExist_ShouldReturnSettings()
{
// Arrange
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
_mockContext.UserSettings.Add(settings);
await _mockContext.SaveChangesAsync();
// Act
Result<UserSettingsEntity?> result = await _sut.GetByUserIdAsync(settings.UserId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(settings.Id, result.Value.Id);
Assert.Equal(settings.UserId, result.Value.UserId);
Assert.Equal(settings.IsPaginationEnabled, result.Value.IsPaginationEnabled);
Assert.Equal(settings.ItemsPerPage, result.Value.ItemsPerPage);
Assert.Equal(settings.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker);
}
[Fact]
public async Task GetByUserIdAsync_WhenSettingsDoNotExist_ShouldReturnNull()
{
// Act
Result<UserSettingsEntity?> result = await _sut.GetByUserIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task UpdateAsync_WhenSettingsExist_ShouldUpdateSettingsAndReturnUpdated()
{
// Arrange
UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create();
_mockContext.UserSettings.Add(existingSettings);
await _mockContext.SaveChangesAsync();
UserSettingsEntity updatedSettings = _userSettingsEntityFixture.Create(
id: existingSettings.Id,
userId: existingSettings.UserId,
isPaginationEnabled: false,
itemsPerPage: 12,
ignoreThePrefixForAlphaPicker: true);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedSettings, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
UserSettingsEntity? modifiedSettings = await _mockContext.UserSettings.FirstOrDefaultAsync(settings => settings.Id == existingSettings.Id);
Assert.NotNull(modifiedSettings);
Assert.Equal(existingSettings.UserId, modifiedSettings.UserId);
Assert.False(modifiedSettings.IsPaginationEnabled);
Assert.Equal(12, modifiedSettings.ItemsPerPage);
Assert.True(modifiedSettings.IgnoreThePrefixForAlphaPicker);
}
[Fact]
public async Task UpdateAsync_WhenSettingsDoNotExist_ShouldReturnError()
{
// Arrange
UserSettingsEntity settings = _userSettingsEntityFixture.Create();
// Act
Result<Updated> result = await _sut.UpdateAsync(settings, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.UserSettings.UserSettingsNotFound, result.FirstError);
}
}
@@ -0,0 +1,141 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
/// <summary>
/// Contains unit tests for the <see cref="UserSettings"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserSettingsTests
{
[Fact]
public void Create_WhenCalledWithoutValues_ShouldCreateSettingsWithDefaultValues()
{
// Arrange
UserId userId = UserId.CreateUnique();
// Act
Result<UserSettings> result = UserSettings.Create(userId);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(userId, result.Value.UserId);
Assert.True(result.Value.IsPaginationEnabled);
Assert.Equal(48, result.Value.ItemsPerPage);
Assert.False(result.Value.IgnoreThePrefixForAlphaPicker);
}
[Fact]
public void Create_WhenCalledWithoutUserId_ShouldCreateSettingsWithDefaultValuesAndGeneratedUserId()
{
// Act
Result<UserSettings> result = UserSettings.Create();
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value.UserId);
Assert.True(result.Value.IsPaginationEnabled);
Assert.Equal(48, result.Value.ItemsPerPage);
Assert.False(result.Value.IgnoreThePrefixForAlphaPicker);
}
[Fact]
public void Create_WhenCalledTwice_ShouldGenerateDistinctIds()
{
// Act
Result<UserSettings> firstResult = UserSettings.Create();
Result<UserSettings> secondResult = UserSettings.Create();
// Assert
Assert.False(firstResult.IsFailure);
Assert.False(secondResult.IsFailure);
Assert.NotEqual(firstResult.Value.UserId.Value, secondResult.Value.UserId.Value);
Assert.NotEqual(firstResult.Value.Id.Value, secondResult.Value.Id.Value);
}
[Fact]
public void Create_WhenCalledWithValidValues_ShouldCreateSettings()
{
// Arrange
UserId userId = UserId.CreateUnique();
// Act
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, ignoreThePrefixForAlphaPicker: true);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(userId, result.Value.UserId);
Assert.False(result.Value.IsPaginationEnabled);
Assert.Equal(24, result.Value.ItemsPerPage);
Assert.True(result.Value.IgnoreThePrefixForAlphaPicker);
}
[Fact]
public void Create_WhenCalledWithValidValues_ShouldGenerateDistinctSettingsIdFromUserId()
{
// Arrange
UserId userId = UserId.CreateUnique();
// Act
Result<UserSettings> result = UserSettings.Create(userId);
// Assert
Assert.False(result.IsFailure);
Assert.NotEqual(result.Value.Id.Value, result.Value.UserId.Value);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void Create_WhenItemsPerPageIsNotPositive_ShouldReturnError(int itemsPerPage)
{
// Arrange
UserId userId = UserId.CreateUnique();
// Act
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError);
}
[Fact]
public void UpdateSettings_WhenCalledWithValidValues_ShouldUpdateSettings()
{
// Arrange
Result<UserSettings> createResult = UserSettings.Create(UserId.CreateUnique());
// Act
Result<Updated> result = createResult.Value.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, ignoreThePrefixForAlphaPicker: true);
// Assert
Assert.False(result.IsFailure);
Assert.False(createResult.Value.IsPaginationEnabled);
Assert.Equal(12, createResult.Value.ItemsPerPage);
Assert.True(createResult.Value.IgnoreThePrefixForAlphaPicker);
}
[Theory]
[InlineData(0)]
[InlineData(-5)]
public void UpdateSettings_WhenItemsPerPageIsNotPositive_ShouldReturnError(int itemsPerPage)
{
// Arrange
Result<UserSettings> createResult = UserSettings.Create(UserId.CreateUnique());
// Act
Result<Updated> result = createResult.Value.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero, result.FirstError);
}
}
@@ -0,0 +1,119 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings;
using Lumina.Contracts.Responses.UsersManagement.Settings;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetUserSettings;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Settings.GetUserSettings;
/// <summary>
/// Contains unit tests for the <see cref="GetUserSettingsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserSettingsEndpointTests
{
private readonly IQueryHandler<GetUserSettingsQuery, Result<UserSettingsResponse>> _mockHandler;
private readonly GetUserSettingsEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
/// </summary>
public GetUserSettingsEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetUserSettingsQuery, Result<UserSettingsResponse>>>();
_sut = Factory.Create<GetUserSettingsEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUserSettingsResponse()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
UserSettingsResponse expectedResponse = new(Guid.NewGuid(), true, 48, false);
_mockHandler.HandleAsync(Arg.Any<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
// Assert
Ok<UserSettingsResponse> okResult = Assert.IsType<Ok<UserSettingsResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Failure("General.Failure", "An error has occurred.");
_mockHandler.HandleAsync(Arg.Any<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
Assert.Equal("General.Failure", problemResult.ProblemDetails.Title);
Assert.Equal("An error has occurred.", problemResult.ProblemDetails.Detail);
Assert.NotNull(problemResult.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetUserSettingsQueryToHandler()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false)));
// Act
await _sut.ExecuteAsync(new EmptyRequest(), cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Any<GetUserSettingsQuery>(),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(info => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false));
}, info.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(new EmptyRequest(), cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,122 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
using Lumina.Contracts.Requests.UsersManagement.Settings;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings;
/// <summary>
/// Contains unit tests for the <see cref="UpdateUserSettingsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateUserSettingsEndpointTests
{
private readonly ICommandHandler<UpdateUserSettingsCommand, Result<Updated>> _mockHandler;
private readonly UpdateUserSettingsEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
/// </summary>
public UpdateUserSettingsEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<UpdateUserSettingsCommand, Result<Updated>>>();
_sut = FastEndpoints.Factory.Create<UpdateUserSettingsEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdatedMarker()
{
// Arrange
UpdateUserSettingsRequest request = new(true, 48, false);
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<Updated> okResult = Assert.IsType<Ok<Updated>>(result);
Assert.Equal(Result.Updated, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
UpdateUserSettingsRequest request = new(true, 0, false);
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Validation("UserSettings.ItemsPerPageMustBeGreaterThanZero", "ItemsPerPage must be greater than zero.");
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
Assert.Equal("General.Validation", problemResult.ProblemDetails.Title);
Assert.NotNull(problemResult.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateUserSettingsCommandToHandler()
{
// Arrange
UpdateUserSettingsRequest request = new(true, 24, true);
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateUserSettingsCommand>(command =>
command.IsPaginationEnabled == request.IsPaginationEnabled &&
command.ItemsPerPage == request.ItemsPerPage &&
command.IgnoreThePrefixForAlphaPicker == request.IgnoreThePrefixForAlphaPicker),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
.Returns(info => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Updated);
}, info.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(new UpdateUserSettingsRequest(true, 48, false), cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}