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,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);
}
}