Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,301 @@
#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.UpdatePlaybackState;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdatePlaybackState;
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;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Commands.UpdatePlaybackState;
/// <summary>
/// Contains unit tests for the <see cref="UpdatePlaybackStateCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaybackStateCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly IValidator<UpdatePlaybackStateCommand> _mockValidator;
private readonly UpdatePlaybackStateCommandHandler _sut;
private readonly UpdatePlaybackStateCommandFixture _updatePlaybackStateCommandFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePlaybackStateCommandHandlerTests"/> class.
/// </summary>
public UpdatePlaybackStateCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_mockValidator = Substitute.For<IValidator<UpdatePlaybackStateCommand>>();
_mockValidator.Validate(Arg.Any<UpdatePlaybackStateCommand>())
.Returns([]);
_sut = new UpdatePlaybackStateCommandHandler(_mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsAndNotPersist()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create();
_mockValidator.Validate(Arg.Any<UpdatePlaybackStateCommand>())
.Returns([ApplicationErrors.UserSettings.VolumeMustBeBetweenZeroAndOne]);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.UserSettings.VolumeMustBeBetweenZeroAndOne, 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
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.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_ShouldReturnErrorAndNotPersist()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.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>());
}
[Fact]
public async Task HandleAsync_WhenSettingsDoNotExist_ShouldInsertTheReportedStateKeepingTheHandEditedSettingsAtTheirDefaults()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(volume: 0.35, isMuted: true);
_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.Volume == 0.35 &&
settings.IsMuted &&
settings.IsPaginationEnabled &&
settings.ItemsPerPage == 48 &&
settings.ShouldAutoplay &&
settings.IsGaplessPlaybackEnabled &&
settings.VuMeterSegmentCount == 12),
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_WhenInsertFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(null));
Error error = Error.Failure("Database.Error", "Failed to insert user settings");
_mockUserSettingsRepository.InsertAsync(Arg.Any<UserSettingsEntity>(), 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSettingsExist_ShouldUpdateTheReportedStateAndPreserveTheHandEditedSettings()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(volume: 0.25, isMuted: true);
UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(
userId: _userId,
volume: 1.0,
isMuted: false,
itemsPerPage: 24,
isPaginationEnabled: false);
_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.Volume == 0.25 &&
settings.IsMuted &&
!settings.IsPaginationEnabled &&
settings.ItemsPerPage == 24),
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_WhenUpdateFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create();
UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(existingSettings));
Error error = Error.Failure("Database.Error", "Failed to update user settings");
_mockUserSettingsRepository.UpdateAsync(Arg.Any<UserSettingsEntity>(), 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFailsAfterInsert_ShouldReturnError()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(null));
_mockUserSettingsRepository.InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
Error error = Error.Failure("Database.Error", "Failed to save changes");
_mockUnitOfWork.SaveChangesAsync(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 _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFailsAfterUpdate_ShouldReturnError()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.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);
Error error = Error.Failure("Database.Error", "Failed to save changes");
_mockUnitOfWork.SaveChangesAsync(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 _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldForwardTheCurrentUserIdAndCancellationToken()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create();
using CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(null));
_mockUserSettingsRepository.InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
// Act
await _sut.HandleAsync(command, cancellationToken);
// Assert
await _mockUserSettingsRepository.Received(1).GetByUserIdAsync(_userId, Arg.Is(cancellationToken));
await _mockUserSettingsRepository.Received(1).InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Is(cancellationToken));
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Is(cancellationToken));
}
[Fact]
public async Task HandleAsync_WhenCancellationIsRequested_ShouldCancelTheOperation()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create();
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationTokenSource.Token)
.Returns(Task.FromCanceled<Result<UserSettingsEntity?>>(cancellationTokenSource.Token));
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(() => _sut.HandleAsync(command, cancellationTokenSource.Token));
await _mockUserSettingsRepository.Received(1).GetByUserIdAsync(_userId, cancellationTokenSource.Token);
}
}
@@ -0,0 +1,125 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState;
using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdatePlaybackState;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Commands.UpdatePlaybackState;
/// <summary>
/// Contains unit tests for the <see cref="UpdatePlaybackStateCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaybackStateCommandValidatorTests
{
private readonly UpdatePlaybackStateCommandValidator _validator = new();
private readonly UpdatePlaybackStateCommandFixture _updatePlaybackStateCommandFixture = new();
[Fact]
public void Validate_WhenVolumeIsNull_ShouldHaveVolumeCannotBeNullErrorAndNoRangeError()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(includeVolume: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VolumeCannotBeNull);
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VolumeMustBeBetweenZeroAndOne);
}
[Theory]
[InlineData(-0.01)] // Just below the minimum.
[InlineData(-1.0)] // Well below the minimum.
[InlineData(double.MinValue)] // Far below the minimum.
public void Validate_WhenVolumeIsBelowZero_ShouldHaveRangeError(double volume)
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(volume: volume);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VolumeMustBeBetweenZeroAndOne);
}
[Theory]
[InlineData(1.01)] // Just above the maximum.
[InlineData(2.0)] // Well above the maximum.
[InlineData(double.MaxValue)] // Far above the maximum.
public void Validate_WhenVolumeIsAboveOne_ShouldHaveRangeError(double volume)
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(volume: volume);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VolumeMustBeBetweenZeroAndOne);
}
[Theory]
[InlineData(0.0)] // The minimum.
[InlineData(0.5)] // A middle value.
[InlineData(1.0)] // The maximum.
public void Validate_WhenVolumeIsInRange_ShouldNotHaveRangeError(double volume)
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(volume: volume);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VolumeMustBeBetweenZeroAndOne);
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VolumeCannotBeNull);
}
[Fact]
public void Validate_WhenIsMutedIsNull_ShouldHaveIsMutedCannotBeNullError()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(includeIsMuted: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.IsMutedCannotBeNull);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Validate_WhenIsMutedIsSpecified_ShouldNotHaveIsMutedCannotBeNullError(bool isMuted)
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(isMuted: isMuted);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.IsMutedCannotBeNull);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,232 @@
#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;
#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>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_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.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker &&
settings.ShouldRenderPdfAsImages == command.ShouldRenderPdfAsImages &&
settings.ShouldPreserveBookStyles == command.ShouldPreserveBookStyles &&
settings.VuMeterOrientation == command.VuMeterOrientation &&
settings.VuMeterSegmentCount == command.VuMeterSegmentCount &&
settings.VuMeterSegmentGap == command.VuMeterSegmentGap &&
settings.VuMeterMediumThreshold == command.VuMeterMediumThreshold &&
settings.VuMeterHighThreshold == command.VuMeterHighThreshold &&
settings.VuMeterShowPeak == command.VuMeterShowPeak &&
settings.VuMeterPeakHoldDurationInMilliseconds == command.VuMeterPeakHoldDurationInMilliseconds &&
settings.VuMeterReleasePerSecond == command.VuMeterReleasePerSecond &&
settings.VuMeterPeakReleasePerSecond == command.VuMeterPeakReleasePerSecond),
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.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker &&
settings.ShouldRenderPdfAsImages == command.ShouldRenderPdfAsImages &&
settings.ShouldPreserveBookStyles == command.ShouldPreserveBookStyles &&
settings.VuMeterOrientation == command.VuMeterOrientation &&
settings.VuMeterSegmentCount == command.VuMeterSegmentCount &&
settings.VuMeterSegmentGap == command.VuMeterSegmentGap &&
settings.VuMeterMediumThreshold == command.VuMeterMediumThreshold &&
settings.VuMeterHighThreshold == command.VuMeterHighThreshold &&
settings.VuMeterShowPeak == command.VuMeterShowPeak &&
settings.VuMeterPeakHoldDurationInMilliseconds == command.VuMeterPeakHoldDurationInMilliseconds &&
settings.VuMeterReleasePerSecond == command.VuMeterReleasePerSecond &&
settings.VuMeterPeakReleasePerSecond == command.VuMeterPeakReleasePerSecond),
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([ApplicationErrors.UserSettings.ItemsPerPageMustBeGreaterThanZero]);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.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>());
}
[Fact]
public async Task HandleAsync_WhenInsertFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(null));
Error error = Error.Failure("Database.Error", "Failed to insert user settings");
_mockUserSettingsRepository.InsertAsync(Arg.Any<UserSettingsEntity>(), 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotSaveChanges()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(existingSettings));
Error error = Error.Failure("Database.Error", "Failed to update user settings");
_mockUserSettingsRepository.UpdateAsync(Arg.Any<UserSettingsEntity>(), 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,515 @@
#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.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#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(ApplicationErrors.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(ApplicationErrors.UserSettings.ItemsPerPageMustBeGreaterThanZero);
}
[Fact]
public void Validate_WhenVuMeterOrientationIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterOrientation: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterOrientationCannotBeNull);
}
[Fact]
public void Validate_WhenVuMeterSegmentCountIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterSegmentCount: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterSegmentCountCannotBeNull);
}
[Fact]
public void Validate_WhenVuMeterSegmentGapIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterSegmentGap: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterSegmentGapCannotBeNull);
}
[Fact]
public void Validate_WhenVuMeterMediumThresholdIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterMediumThreshold: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterMediumThresholdCannotBeNull);
}
[Fact]
public void Validate_WhenVuMeterHighThresholdIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterHighThreshold: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterHighThresholdCannotBeNull);
}
[Fact]
public void Validate_WhenVuMeterShowPeakIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterShowPeak: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterShowPeakCannotBeNull);
}
[Fact]
public void Validate_WhenVuMeterPeakHoldDurationIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterPeakHoldDurationInMilliseconds: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterPeakHoldDurationCannotBeNull);
}
[Fact]
public void Validate_WhenVuMeterReleasePerSecondIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterReleasePerSecond: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterReleasePerSecondCannotBeNull);
}
[Fact]
public void Validate_WhenVuMeterPeakReleasePerSecondIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(includeVuMeterPeakReleasePerSecond: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterPeakReleasePerSecondCannotBeNull);
}
[Theory]
[InlineData(999)] // A value that is not a defined member of the enumeration.
[InlineData(-1)] // A negative value that is not a defined member of the enumeration.
public void Validate_WhenVuMeterOrientationIsNotDefined_ShouldHaveValidationError(int vuMeterOrientationValue)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterOrientation: (VuMeterOrientation)vuMeterOrientationValue);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.InvalidVuMeterOrientation);
}
[Theory]
[InlineData(VuMeterOrientation.Vertical)]
[InlineData(VuMeterOrientation.Horizontal)]
public void Validate_WhenVuMeterOrientationIsDefined_ShouldNotHaveValidationError(VuMeterOrientation vuMeterOrientation)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterOrientation: vuMeterOrientation);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.InvalidVuMeterOrientation);
}
[Theory]
[InlineData(0)] // Below the minimum.
[InlineData(-1)] // Negative.
[InlineData(129)] // Above the maximum.
[InlineData(int.MaxValue)] // Far above the maximum.
public void Validate_WhenVuMeterSegmentCountIsOutOfRange_ShouldHaveValidationError(int vuMeterSegmentCount)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterSegmentCount: vuMeterSegmentCount);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterSegmentCountMustBeBetweenOneAndOneHundredTwentyEight);
}
[Theory]
[InlineData(1)] // The minimum.
[InlineData(64)] // A middle value.
[InlineData(128)] // The maximum.
public void Validate_WhenVuMeterSegmentCountIsInRange_ShouldNotHaveValidationError(int vuMeterSegmentCount)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterSegmentCount: vuMeterSegmentCount);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VuMeterSegmentCountMustBeBetweenOneAndOneHundredTwentyEight);
}
[Theory]
[InlineData(-1)] // Below the minimum.
[InlineData(33)] // Above the maximum.
[InlineData(int.MinValue)] // Far below the minimum.
public void Validate_WhenVuMeterSegmentGapIsOutOfRange_ShouldHaveValidationError(int vuMeterSegmentGap)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterSegmentGap: vuMeterSegmentGap);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterSegmentGapMustBeBetweenZeroAndThirtyTwo);
}
[Theory]
[InlineData(0)] // The minimum.
[InlineData(16)] // A middle value.
[InlineData(32)] // The maximum.
public void Validate_WhenVuMeterSegmentGapIsInRange_ShouldNotHaveValidationError(int vuMeterSegmentGap)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterSegmentGap: vuMeterSegmentGap);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VuMeterSegmentGapMustBeBetweenZeroAndThirtyTwo);
}
[Theory]
[InlineData(-0.01)] // Just below the minimum.
[InlineData(1.01)] // Just above the maximum.
[InlineData(double.MinValue)] // Far below the minimum.
public void Validate_WhenVuMeterMediumThresholdIsOutOfRange_ShouldHaveValidationError(double vuMeterMediumThreshold)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterMediumThreshold: vuMeterMediumThreshold,
vuMeterHighThreshold: 1.0);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterMediumThresholdMustBeBetweenZeroAndOne);
}
[Theory]
[InlineData(0.0)] // The minimum.
[InlineData(0.5)] // A middle value.
[InlineData(1.0)] // The maximum.
public void Validate_WhenVuMeterMediumThresholdIsInRange_ShouldNotHaveValidationError(double vuMeterMediumThreshold)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterMediumThreshold: vuMeterMediumThreshold,
vuMeterHighThreshold: 1.0);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VuMeterMediumThresholdMustBeBetweenZeroAndOne);
}
[Theory]
[InlineData(-0.01)] // Just below the minimum.
[InlineData(1.01)] // Just above the maximum.
[InlineData(double.MaxValue)] // Far above the maximum.
public void Validate_WhenVuMeterHighThresholdIsOutOfRange_ShouldHaveValidationError(double vuMeterHighThreshold)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterMediumThreshold: 0.0,
vuMeterHighThreshold: vuMeterHighThreshold);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterHighThresholdMustBeBetweenZeroAndOne);
}
[Fact]
public void Validate_WhenVuMeterHighThresholdIsAtTheMinimum_ShouldNotHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterMediumThreshold: 0.0,
vuMeterHighThreshold: 0.0);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VuMeterHighThresholdMustBeBetweenZeroAndOne);
}
[Fact]
public void Validate_WhenVuMeterHighThresholdIsAtTheMaximum_ShouldNotHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterMediumThreshold: 0.5,
vuMeterHighThreshold: 1.0);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VuMeterHighThresholdMustBeBetweenZeroAndOne);
}
[Fact]
public void Validate_WhenVuMeterHighThresholdIsLowerThanMediumThreshold_ShouldHaveValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterMediumThreshold: 0.9,
vuMeterHighThreshold: 0.1);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterHighThresholdMustBeGreaterThanOrEqualToMediumThreshold);
}
[Theory]
[InlineData(0.5, 0.5)] // The thresholds are equal.
[InlineData(0.4, 0.9)] // The high threshold is greater than the medium one.
public void Validate_WhenVuMeterHighThresholdIsGreaterThanOrEqualToMediumThreshold_ShouldNotHaveValidationError(
double vuMeterMediumThreshold,
double vuMeterHighThreshold)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterMediumThreshold: vuMeterMediumThreshold,
vuMeterHighThreshold: vuMeterHighThreshold);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VuMeterHighThresholdMustBeGreaterThanOrEqualToMediumThreshold);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Validate_WhenVuMeterShowPeakIsSpecified_ShouldNotHaveValidationError(bool vuMeterShowPeak)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(vuMeterShowPeak: vuMeterShowPeak);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VuMeterShowPeakCannotBeNull);
}
[Theory]
[InlineData(-1)] // Below the minimum.
[InlineData(10001)] // Above the maximum.
[InlineData(int.MinValue)] // Far below the minimum.
public void Validate_WhenVuMeterPeakHoldDurationIsOutOfRange_ShouldHaveValidationError(int vuMeterPeakHoldDurationInMilliseconds)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterPeakHoldDurationInMilliseconds: vuMeterPeakHoldDurationInMilliseconds);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterPeakHoldDurationMustBeBetweenZeroAndTenThousandMilliseconds);
}
[Theory]
[InlineData(0)] // The minimum.
[InlineData(650)] // A middle value.
[InlineData(10000)] // The maximum.
public void Validate_WhenVuMeterPeakHoldDurationIsInRange_ShouldNotHaveValidationError(int vuMeterPeakHoldDurationInMilliseconds)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterPeakHoldDurationInMilliseconds: vuMeterPeakHoldDurationInMilliseconds);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VuMeterPeakHoldDurationMustBeBetweenZeroAndTenThousandMilliseconds);
}
[Theory]
[InlineData(-0.01)] // Just below the minimum.
[InlineData(100.01)] // Just above the maximum.
[InlineData(double.MinValue)] // Far below the minimum.
public void Validate_WhenVuMeterReleasePerSecondIsOutOfRange_ShouldHaveValidationError(double vuMeterReleasePerSecond)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterReleasePerSecond: vuMeterReleasePerSecond);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterReleasePerSecondMustBeBetweenZeroAndOneHundred);
}
[Theory]
[InlineData(0.0)] // The minimum.
[InlineData(3.0)] // A middle value.
[InlineData(100.0)] // The maximum.
public void Validate_WhenVuMeterReleasePerSecondIsInRange_ShouldNotHaveValidationError(double vuMeterReleasePerSecond)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterReleasePerSecond: vuMeterReleasePerSecond);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VuMeterReleasePerSecondMustBeBetweenZeroAndOneHundred);
}
[Theory]
[InlineData(-0.01)] // Just below the minimum.
[InlineData(100.01)] // Just above the maximum.
[InlineData(double.MaxValue)] // Far above the maximum.
public void Validate_WhenVuMeterPeakReleasePerSecondIsOutOfRange_ShouldHaveValidationError(double vuMeterPeakReleasePerSecond)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterPeakReleasePerSecond: vuMeterPeakReleasePerSecond);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(ApplicationErrors.UserSettings.VuMeterPeakReleasePerSecondMustBeBetweenZeroAndOneHundred);
}
[Theory]
[InlineData(0.0)] // The minimum.
[InlineData(0.65)] // A middle value.
[InlineData(100.0)] // The maximum.
public void Validate_WhenVuMeterPeakReleasePerSecondIsInRange_ShouldNotHaveValidationError(double vuMeterPeakReleasePerSecond)
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create(
vuMeterPeakReleasePerSecond: vuMeterPeakReleasePerSecond);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(ApplicationErrors.UserSettings.VuMeterPeakReleasePerSecondMustBeBetweenZeroAndOneHundred);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
{
// Arrange
UpdateUserSettingsCommand command = _updateUserSettingsCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,149 @@
#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.Core.UsersManagement.Settings.Queries.GetPlaybackState;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Queries.GetPlaybackState;
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;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Queries.GetPlaybackState;
/// <summary>
/// Contains unit tests for the <see cref="GetPlaybackStateQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackStateQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly GetPlaybackStateQueryHandler _sut;
private readonly GetPlaybackStateQueryFixture _getPlaybackStateQueryFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackStateQueryHandlerTests"/> class.
/// </summary>
public GetPlaybackStateQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_mockCurrentUserService.UserId.Returns(_userId);
_sut = new GetPlaybackStateQueryHandler(_mockCurrentUserService, _mockUnitOfWork);
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedWithoutReadingSettings()
{
// Arrange
GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<PlaybackStateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByUserIdReturnsError_ShouldReturnError()
{
// Arrange
GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to retrieve user settings");
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<PlaybackStateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenSettingsDoNotExist_ShouldReturnTheDefaultPlaybackState()
{
// Arrange
GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(null));
// Act
Result<PlaybackStateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1.0, result.Value.Volume);
Assert.False(result.Value.IsMuted);
}
[Fact]
public async Task HandleAsync_WhenSettingsExist_ShouldReturnTheStoredPlaybackState()
{
// Arrange
GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create();
UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: _userId, volume: 0.42, isMuted: true);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(storedSettings));
// Act
Result<PlaybackStateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(0.42, result.Value.Volume);
Assert.True(result.Value.IsMuted);
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldForwardTheCurrentUserIdAndCancellationToken()
{
// Arrange
GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create();
using CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(null));
// Act
await _sut.HandleAsync(query, cancellationToken);
// Assert
await _mockUserSettingsRepository.Received(1).GetByUserIdAsync(_userId, Arg.Is(cancellationToken));
}
[Fact]
public async Task HandleAsync_WhenCancellationIsRequested_ShouldCancelTheOperation()
{
// Arrange
GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create();
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationTokenSource.Token)
.Returns(Task.FromCanceled<Result<UserSettingsEntity?>>(cancellationTokenSource.Token));
// Act & Assert
await Assert.ThrowsAsync<TaskCanceledException>(() => _sut.HandleAsync(query, cancellationTokenSource.Token));
await _mockUserSettingsRepository.Received(1).GetByUserIdAsync(_userId, cancellationTokenSource.Token);
}
}
@@ -0,0 +1,122 @@
#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.Application.Fixtures.Core.UsersManagement.Settings.Queries.GetUserSettings;
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 GetUserSettingsQueryFixture _getUserSettingsQueryFixture = 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>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_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 = _getUserSettingsQueryFixture.Create();
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.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker);
}
[Fact]
public async Task HandleAsync_WhenSettingsDoNotExist_ShouldReturnDefaultSettings()
{
// Arrange
GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create();
_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.NotEqual(Guid.Empty, result.Value.UserId);
Assert.True(result.Value.IsPaginationEnabled);
Assert.Equal(48, result.Value.ItemsPerPage);
Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create();
_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 = _getUserSettingsQueryFixture.Create();
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);
}
}