mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 14:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+451
@@ -0,0 +1,451 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
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.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddFavoriteCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly IDomainEventsQueue _mockDomainEventsQueue;
|
||||
private readonly IFavoriteRepository _mockFavoriteRepository;
|
||||
private readonly IValidator<AddFavoriteCommand> _mockValidator;
|
||||
private readonly AddFavoriteCommandHandler _sut;
|
||||
private readonly AddFavoriteCommandFixture _addFavoriteCommandFixture = new();
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly Guid _userId = Guid.NewGuid();
|
||||
private readonly Guid _libraryId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public AddFavoriteCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
|
||||
_mockFavoriteRepository = Substitute.For<IFavoriteRepository>();
|
||||
|
||||
_mockUnitOfWork.FavoriteRepository.Returns(_mockFavoriteRepository);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockFavoriteRepository.GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<Guid?>(_libraryId));
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null));
|
||||
_mockFavoriteRepository.InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
_mockValidator = Substitute.For<IValidator<AddFavoriteCommand>>();
|
||||
_mockValidator.Validate(Arg.Any<AddFavoriteCommand>()).Returns([]);
|
||||
|
||||
_sut = new AddFavoriteCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockAuthorizationService, _mockDomainEventsQueue, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepositories()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = DomainErrors.Favorites.FavoriteMediaKindIsInvalid;
|
||||
_mockValidator.Validate(Arg.Any<AddFavoriteCommand>()).Returns([error]);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_ = _mockCurrentUserService.DidNotReceive().UserId;
|
||||
await _mockFavoriteRepository.DidNotReceive().GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadTheRepositories()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.None)] // The default value, which is not a kind that can be favorited.
|
||||
[InlineData(FavoriteMediaKind.Video)] // Video libraries are not catalogued yet.
|
||||
[InlineData(FavoriteMediaKind.Photo)] // Photo libraries are not catalogued yet.
|
||||
public async Task HandleAsync_WhenMediaKindIsNotSupported_ShouldReturnNotSupportedAndNotResolveTheLibrary(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Favorites.FavoriteMediaKindIsNotSupported, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheMediaItemLibraryLookupFails_ShouldReturnThatErrorAndNotAuthorizeOrReadTheFavorite()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The media item library could not be read.");
|
||||
_mockFavoriteRepository.GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist, nameof(DomainErrors.Music.ArtistNotFound))] // The artist does not exist.
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum, nameof(DomainErrors.Music.AlbumNotFound))] // The album does not exist.
|
||||
[InlineData(FavoriteMediaKind.MusicTrack, nameof(DomainErrors.Music.TrackNotFound))] // The track does not exist.
|
||||
[InlineData(FavoriteMediaKind.Book, nameof(DomainErrors.WrittenContent.BookNotFound))] // The book does not exist.
|
||||
public async Task HandleAsync_WhenTheMediaItemHasNoLibrary_ShouldReturnTheMediaKindSpecificNotFoundError(FavoriteMediaKind mediaKind, string expectedErrorDescription)
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: mediaKind);
|
||||
_mockFavoriteRepository.GetMediaItemLibraryIdAsync(Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<Guid?>(null));
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedErrorDescription, result.FirstError.Description);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryAccessIsDenied_ShouldReturnTheMediaKindSpecificNotFoundErrorAndNotReadTheFavorite()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: FavoriteMediaKind.MusicTrack);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(nameof(DomainErrors.Music.TrackNotFound), result.FirstError.Description);
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheExistingFavoriteReadFails_ShouldReturnThatErrorAndNotInsert()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The existing favorite could not be read.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheItemIsAlreadyAFavorite_ShouldReturnTheStoredFavoriteWithoutInsertingOrRaisingAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
DateTime createdOnUtc = new(2024, 5, 6, 7, 8, 9, DateTimeKind.Utc);
|
||||
FavoriteEntity existingFavorite = _favoriteEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: command.MediaKind!.Value,
|
||||
mediaItemId: command.MediaItemId!.Value,
|
||||
createdOnUtc: createdOnUtc);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(existingFavorite));
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(existingFavorite.Id, result.Value.Id);
|
||||
Assert.Equal(createdOnUtc, result.Value.FavoritedOnUtc);
|
||||
await _mockFavoriteRepository.DidNotReceive().InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenInsertFails_ShouldReturnThatErrorAndNotSaveChanges()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The favorite could not be inserted.");
|
||||
_mockFavoriteRepository.InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithANonUniqueConstraintError_ShouldReturnThatErrorAndNotRaiseAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The changes could not be saved.");
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockUnitOfWork.DidNotReceive().ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAUniqueConstraintViolationAndAConcurrentFavoriteExists_ShouldReturnTheConcurrentFavoriteWithoutRaisingAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
DateTime createdOnUtc = new(2024, 7, 8, 9, 10, 11, DateTimeKind.Utc);
|
||||
FavoriteEntity concurrentFavorite = _favoriteEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: command.MediaKind!.Value,
|
||||
mediaItemId: command.MediaItemId!.Value,
|
||||
createdOnUtc: createdOnUtc);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), Result.From<FavoriteEntity?>(concurrentFavorite));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(concurrentFavorite.Id, result.Value.Id);
|
||||
Assert.Equal(createdOnUtc, result.Value.FavoritedOnUtc);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
await _mockFavoriteRepository.Received(2).GetByMediaItemIdForUserAsync(_userId, command.MediaKind!.Value, command.MediaItemId!.Value, Arg.Is<bool>(shouldTrackEntities => !shouldTrackEntities), Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAUniqueConstraintViolationAndTheConcurrentFavoriteIsMissing_ShouldReturnTheSaveError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), Result.From<FavoriteEntity?>(null));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAUniqueConstraintViolationAndTheReReadFails_ShouldReturnTheReReadError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The concurrent favorite could not be read.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), error);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSuccessful_ShouldInsertSaveEnqueueOnceAndReturnThePersistedFavorite()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: FavoriteMediaKind.MusicAlbum);
|
||||
DateTime createdOnUtc = new(2024, 9, 10, 11, 12, 13, DateTimeKind.Utc);
|
||||
FavoriteEntity persistedFavorite = _favoriteEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: command.MediaKind!.Value,
|
||||
mediaItemId: command.MediaItemId!.Value,
|
||||
createdOnUtc: createdOnUtc);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), Result.From<FavoriteEntity?>(persistedFavorite));
|
||||
FavoriteEntity? insertedEntity = null;
|
||||
_mockFavoriteRepository.InsertAsync(Arg.Do<FavoriteEntity>(favorite => insertedEntity = favorite), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(persistedFavorite.Id, result.Value.Id);
|
||||
Assert.Equal(persistedFavorite.MediaKind, result.Value.MediaKind);
|
||||
Assert.Equal(persistedFavorite.MediaItemId, result.Value.MediaItemId);
|
||||
Assert.Equal(createdOnUtc, result.Value.FavoritedOnUtc);
|
||||
Assert.NotNull(insertedEntity);
|
||||
Assert.NotEqual(Guid.Empty, insertedEntity!.Id);
|
||||
Assert.Equal(_userId, insertedEntity.UserId);
|
||||
Assert.Equal(command.MediaKind!.Value, insertedEntity.MediaKind);
|
||||
Assert.Equal(command.MediaItemId!.Value, insertedEntity.MediaItemId);
|
||||
Assert.Equal(Guid.Empty, insertedEntity.CreatedBy);
|
||||
Assert.Null(insertedEntity.UpdatedOnUtc);
|
||||
Assert.Null(insertedEntity.UpdatedBy);
|
||||
await _mockFavoriteRepository.Received(1).InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is FavoriteAddedDomainEvent));
|
||||
await _mockFavoriteRepository.Received(2).GetByMediaItemIdForUserAsync(_userId, command.MediaKind!.Value, command.MediaItemId!.Value, Arg.Is<bool>(shouldTrackEntities => !shouldTrackEntities), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenThePersistedFavoriteReadFails_ShouldReturnThatErrorAndNotEnqueueTheAddedEvent()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The persisted favorite could not be read.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenThePersistedFavoriteIsMissing_ShouldReturnFavoriteNotFoundWithoutEnqueuingTheAddedEvent()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), Result.From<FavoriteEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<FavoriteResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Favorites.FavoriteNotFound, result.FirstError);
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldScopeEveryRepositoryCallToTheCurrentUserTheMediaKindAndTheMediaItemAndForwardTheCancellationToken()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: FavoriteMediaKind.Book);
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
FavoriteEntity persistedFavorite = _favoriteEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: command.MediaKind!.Value,
|
||||
mediaItemId: command.MediaItemId!.Value);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null), Result.From<FavoriteEntity?>(persistedFavorite));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(command, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockFavoriteRepository.Received(1).GetMediaItemLibraryIdAsync(command.MediaKind!.Value, command.MediaItemId!.Value, Arg.Is(cancellationToken));
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId,
|
||||
Arg.Is<PolicyContext>(context => context is LibraryOwnershipPolicyContext && ((LibraryOwnershipPolicyContext)context).LibraryId == _libraryId),
|
||||
Arg.Is(cancellationToken));
|
||||
await _mockFavoriteRepository.Received(2).GetByMediaItemIdForUserAsync(_userId, command.MediaKind!.Value, command.MediaItemId!.Value, Arg.Is<bool>(shouldTrackEntities => !shouldTrackEntities), Arg.Is(cancellationToken));
|
||||
await _mockFavoriteRepository.Received(1).InsertAsync(Arg.Any<FavoriteEntity>(), Arg.Is(cancellationToken));
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddFavoriteCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteCommandValidatorTests
|
||||
{
|
||||
private readonly AddFavoriteCommandValidator _validator = new();
|
||||
private readonly AddFavoriteCommandFixture _addFavoriteCommandFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsUndefined_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: (FavoriteMediaKind)int.MaxValue);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNone_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: FavoriteMediaKind.None);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist)] // A catalogued music kind.
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum)] // A catalogued music kind.
|
||||
[InlineData(FavoriteMediaKind.MusicTrack)] // A catalogued music kind.
|
||||
[InlineData(FavoriteMediaKind.Book)] // A catalogued written content kind.
|
||||
[InlineData(FavoriteMediaKind.Video)] // A planned kind is still a defined enumeration member.
|
||||
[InlineData(FavoriteMediaKind.Photo)] // A planned kind is still a defined enumeration member.
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaItemIdIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(includeMediaItemId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaItemIdIsTheEmptyGuid_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create(mediaItemId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddFavoriteCommand command = _addFavoriteCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Commands.RemoveFavorite;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
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.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RemoveFavoriteCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IDomainEventsQueue _mockDomainEventsQueue;
|
||||
private readonly IFavoriteRepository _mockFavoriteRepository;
|
||||
private readonly IValidator<RemoveFavoriteCommand> _mockValidator;
|
||||
private readonly RemoveFavoriteCommandHandler _sut;
|
||||
private readonly RemoveFavoriteCommandFixture _removeFavoriteCommandFixture = new();
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly Guid _userId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public RemoveFavoriteCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
|
||||
_mockFavoriteRepository = Substitute.For<IFavoriteRepository>();
|
||||
|
||||
_mockUnitOfWork.FavoriteRepository.Returns(_mockFavoriteRepository);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(null));
|
||||
_mockFavoriteRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Deleted);
|
||||
|
||||
_mockValidator = Substitute.For<IValidator<RemoveFavoriteCommand>>();
|
||||
_mockValidator.Validate(Arg.Any<RemoveFavoriteCommand>()).Returns([]);
|
||||
|
||||
_sut = new RemoveFavoriteCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockDomainEventsQueue, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepositories()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
Error error = DomainErrors.Favorites.FavoriteMediaKindIsInvalid;
|
||||
_mockValidator.Validate(Arg.Any<RemoveFavoriteCommand>()).Returns([error]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_ = _mockCurrentUserService.DidNotReceive().UserId;
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadTheFavorite()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheFavoriteReadFails_ShouldReturnThatError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The favorite could not be read.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheFavoriteIsAbsent_ShouldReturnDeletedWithoutDeletingOrRaisingAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
await _mockFavoriteRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenDeleteFails_ShouldReturnThatErrorAndNotSaveChanges()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
Error error = Error.Failure("Persistence.Failure", "The favorite could not be deleted.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite));
|
||||
_mockFavoriteRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithANonConcurrencyError_ShouldReturnThatErrorAndNotRaiseAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
Error error = Error.Failure("Persistence.Failure", "The changes could not be saved.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockUnitOfWork.DidNotReceive().ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAConcurrencyConflictAndTheFavoriteStillExists_ShouldReturnTheSaveError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite), Result.From<FavoriteEntity?>(favorite));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.ConcurrencyConflict);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.ConcurrencyConflict, result.FirstError);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAConcurrencyConflictAndTheFavoriteIsGone_ShouldReturnDeletedWithoutRaisingAnEvent()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite), Result.From<FavoriteEntity?>(null));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.ConcurrencyConflict);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveFailsWithAConcurrencyConflictAndTheReReadFails_ShouldReturnThatError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
Error error = Error.Failure("Persistence.Failure", "The remaining favorite could not be read.");
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite), error);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(ApplicationErrors.Persistence.ConcurrencyConflict);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
_mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any<IDomainEvent>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSuccessful_ShouldDeleteTheFavoriteSaveOnceAndRaiseExactlyOneRemovedEvent()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(mediaKind: nameof(FavoriteMediaKind.Book));
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
await _mockFavoriteRepository.Received(1).GetByMediaItemIdForUserAsync(_userId, FavoriteMediaKind.Book, favorite.MediaItemId, Arg.Is<bool>(shouldTrackEntities => shouldTrackEntities), Arg.Any<CancellationToken>());
|
||||
await _mockFavoriteRepository.Received(1).DeleteByIdAsync(favorite.Id, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Is<IDomainEvent>(domainEvent => domainEvent is FavoriteRemovedDomainEvent));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldScopeEveryCallToTheStoredFavoriteAndForwardTheCancellationToken()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
FavoriteEntity favorite = CreateFavoriteFrom(command);
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
_mockFavoriteRepository.GetByMediaItemIdForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<FavoriteEntity?>(favorite));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(command, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockFavoriteRepository.Received(1).GetByMediaItemIdForUserAsync(_userId, favorite.MediaKind, favorite.MediaItemId, Arg.Is<bool>(shouldTrackEntities => shouldTrackEntities), Arg.Is(cancellationToken));
|
||||
await _mockFavoriteRepository.Received(1).DeleteByIdAsync(favorite.Id, Arg.Is(cancellationToken));
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a stored favorite entity that matches the media kind and media item of <paramref name="command"/>.
|
||||
/// </summary>
|
||||
/// <param name="command">The command whose route values describe the favorite.</param>
|
||||
/// <returns>The created <see cref="FavoriteEntity"/>.</returns>
|
||||
private FavoriteEntity CreateFavoriteFrom(RemoveFavoriteCommand command)
|
||||
{
|
||||
return _favoriteEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: Enum.Parse<FavoriteMediaKind>(command.MediaKind!, ignoreCase: true),
|
||||
mediaItemId: Guid.Parse(command.MediaItemId!));
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Commands.RemoveFavorite;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="RemoveFavoriteCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteCommandValidatorTests
|
||||
{
|
||||
private readonly RemoveFavoriteCommandValidator _validator = new();
|
||||
private readonly RemoveFavoriteCommandFixture _removeFavoriteCommandFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // The media kind is empty.
|
||||
[InlineData(" ")] // The media kind is whitespace only.
|
||||
[InlineData("Hologram")] // The media kind is not a member of the enumeration.
|
||||
[InlineData("None")] // The default value is not a kind that can be favorited.
|
||||
[InlineData("none")] // The default value, matched case insensitively.
|
||||
[InlineData("0")] // The media kind is a numeric route value, which the validator rejects by name.
|
||||
[InlineData("1")] // A numeric route value that parses to a defined member, which the name check rejects.
|
||||
[InlineData("MusicTrack,Book")] // A comma separated list is not a single member name.
|
||||
[InlineData("../MusicTrack")] // A path-like value is not a member name.
|
||||
public void Validate_WhenMediaKindIsEmptyOrNotAMemberName_ShouldHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("musictrack")] // The member name is lower case.
|
||||
[InlineData("BoOk")] // The member name is mixed case.
|
||||
public void Validate_WhenMediaKindUsesDifferentCasing_ShouldNotHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaItemIdIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(includeMediaItemId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // The media item Id is empty.
|
||||
[InlineData(" ")] // The media item Id is whitespace only.
|
||||
[InlineData("not-a-guid")] // The media item Id is not a Guid.
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // The media item Id is the empty Guid.
|
||||
public void Validate_WhenMediaItemIdIsEmptyOrInvalid_ShouldHaveValidationError(string mediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(mediaItemId: mediaItemId);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBothValuesAreInvalid_ShouldHaveBothValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
RemoveFavoriteCommand command = _removeFavoriteCommandFixture.Create(
|
||||
mediaKind: "Hologram",
|
||||
mediaItemId: "not-a-guid");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
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.Favorites.Queries.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFavoriteStatusQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IFavoriteRepository _mockFavoriteRepository;
|
||||
private readonly IValidator<GetFavoriteStatusQuery> _mockValidator;
|
||||
private readonly GetFavoriteStatusQueryHandler _sut;
|
||||
private readonly GetFavoriteStatusQueryFixture _getFavoriteStatusQueryFixture = new();
|
||||
private readonly Guid _userId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetFavoriteStatusQueryHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockFavoriteRepository = Substitute.For<IFavoriteRepository>();
|
||||
|
||||
_mockUnitOfWork.FavoriteRepository.Returns(_mockFavoriteRepository);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockFavoriteRepository.GetFavoritedMediaItemIdsForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<Guid>>([]));
|
||||
|
||||
_mockValidator = Substitute.For<IValidator<GetFavoriteStatusQuery>>();
|
||||
_mockValidator.Validate(Arg.Any<GetFavoriteStatusQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetFavoriteStatusQueryHandler(_mockUnitOfWork, _mockCurrentUserService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotReadTheRepositories()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create();
|
||||
Error error = DomainErrors.Favorites.FavoriteMediaItemIdsCannotBeEmpty;
|
||||
_mockValidator.Validate(Arg.Any<GetFavoriteStatusQuery>()).Returns([error]);
|
||||
|
||||
// Act
|
||||
Result<FavoriteStatusResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_ = _mockCurrentUserService.DidNotReceive().UserId;
|
||||
await _mockFavoriteRepository.DidNotReceive().GetFavoritedMediaItemIdsForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadTheRepositories()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<FavoriteStatusResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().GetFavoritedMediaItemIdsForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheRepositoryFails_ShouldReturnThatError()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The favorite status could not be read.");
|
||||
_mockFavoriteRepository.GetFavoritedMediaItemIdsForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<FavoriteStatusResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheQueryContainsDuplicateIds_ShouldCheckEveryDistinctIdAndReturnTheFavoritedIds()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstId = Guid.NewGuid();
|
||||
Guid secondId = Guid.NewGuid();
|
||||
Guid thirdId = Guid.NewGuid();
|
||||
List<Guid> requestedIds = [firstId, secondId, firstId, thirdId, secondId];
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.MusicAlbum,
|
||||
mediaItemIds: requestedIds);
|
||||
List<Guid> favoritedIds = [firstId, thirdId];
|
||||
_mockFavoriteRepository.GetFavoritedMediaItemIdsForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<Guid>>(favoritedIds));
|
||||
|
||||
// Act
|
||||
Result<FavoriteStatusResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(favoritedIds, result.Value.FavoritedMediaItemIds);
|
||||
await _mockFavoriteRepository.Received(1).GetFavoritedMediaItemIdsForUserAsync(
|
||||
_userId,
|
||||
FavoriteMediaKind.MusicAlbum,
|
||||
Arg.Is<IReadOnlyCollection<Guid>>(ids => ids.Count == 3 && ids.Contains(firstId) && ids.Contains(secondId) && ids.Contains(thirdId)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenNoRequestedItemIsFavorited_ShouldReturnAnEmptyStatusList()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<FavoriteStatusResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value.FavoritedMediaItemIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldForwardTheCurrentUserTheMediaKindAndTheCancellationToken()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create(mediaKind: FavoriteMediaKind.Book);
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockFavoriteRepository.Received(1).GetFavoritedMediaItemIdsForUserAsync(
|
||||
_userId,
|
||||
FavoriteMediaKind.Book,
|
||||
Arg.Any<IReadOnlyCollection<Guid>>(),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFavoriteStatusQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusQueryValidatorTests
|
||||
{
|
||||
private readonly GetFavoriteStatusQueryValidator _validator = new();
|
||||
private readonly GetFavoriteStatusQueryFixture _getFavoriteStatusQueryFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsUndefined_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create(mediaKind: (FavoriteMediaKind)int.MaxValue);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNone_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create(mediaKind: FavoriteMediaKind.None);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaItemIdsAreNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create(includeMediaItemIds: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdsCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaItemIdsAreEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create(mediaItemIds: []);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdsCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenThereAreMoreThanOneHundredMediaItemIds_ShouldHaveMaximumCountValidationError()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> mediaItemIds = [.. Enumerable.Range(0, 101).Select(_ => Guid.NewGuid())];
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create(mediaItemIds: mediaItemIds);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdsExceedMaximumCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenThereAreExactlyOneHundredMediaItemIds_ShouldNotHaveMaximumCountValidationError()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> mediaItemIds = [.. Enumerable.Range(0, 100).Select(_ => Guid.NewGuid())];
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create(mediaItemIds: mediaItemIds);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Favorites.FavoriteMediaItemIdsExceedMaximumCount);
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenOneMediaItemIdIsTheEmptyGuid_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
List<Guid> mediaItemIds = [Guid.NewGuid(), Guid.Empty];
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create(mediaItemIds: mediaItemIds);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoriteStatusQuery query = _getFavoriteStatusQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Queries.GetFavorites;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
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.Favorites.Queries.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFavoritesQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly IFavoriteRepository _mockFavoriteRepository;
|
||||
private readonly IValidator<GetFavoritesQuery> _mockValidator;
|
||||
private readonly GetFavoritesQueryHandler _sut;
|
||||
private readonly GetFavoritesQueryFixture _getFavoritesQueryFixture = new();
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly FavoriteItemDtoFixture _favoriteItemDtoFixture = new();
|
||||
private readonly FavoriteItemDisplayDtoFixture _favoriteItemDisplayDtoFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<FavoriteItemDto> _paginatedResultDtoFixture = new();
|
||||
private readonly Guid _userId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetFavoritesQueryHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockFavoriteRepository = Substitute.For<IFavoriteRepository>();
|
||||
|
||||
_mockUnitOfWork.FavoriteRepository.Returns(_mockFavoriteRepository);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockFavoriteRepository.GetAllForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind?>(), Arg.Any<PaginationDataDto?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_paginatedResultDtoFixture.Create()));
|
||||
|
||||
_mockValidator = Substitute.For<IValidator<GetFavoritesQuery>>();
|
||||
_mockValidator.Validate(Arg.Any<GetFavoritesQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetFavoritesQueryHandler(_mockUnitOfWork, _mockCurrentUserService, _mockAuthorizationService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotReadTheRepositoriesOrAuthorize()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create();
|
||||
Error error = DomainErrors.Favorites.FavoriteMediaKindIsInvalid;
|
||||
_mockValidator.Validate(Arg.Any<GetFavoritesQuery>()).Returns([error]);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<FavoriteItemResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_ = _mockCurrentUserService.DidNotReceive().UserId;
|
||||
await _mockFavoriteRepository.DidNotReceive().GetAllForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind?>(), Arg.Any<PaginationDataDto?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadTheRepositories()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<FavoriteItemResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockFavoriteRepository.DidNotReceive().GetAllForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind?>(), Arg.Any<PaginationDataDto?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheRepositoryFails_ShouldReturnThatErrorAndNotAuthorize()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The favorites could not be read.");
|
||||
_mockFavoriteRepository.GetAllForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind?>(), Arg.Any<PaginationDataDto?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<FavoriteItemResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheItemsHaveNoDisplayData_ShouldKeepEveryRowUnavailableWithEmptyDisplayFields()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteItemDto firstItem = _favoriteItemDtoFixture.Create(includeDisplay: false);
|
||||
FavoriteItemDto secondItem = _favoriteItemDtoFixture.Create(includeDisplay: false);
|
||||
PaginatedResultDto<FavoriteItemDto> page = _paginatedResultDtoFixture.Create(
|
||||
data: [firstItem, secondItem],
|
||||
currentPage: 2,
|
||||
perPage: 5,
|
||||
count: 12,
|
||||
numberOfPages: 3);
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create();
|
||||
_mockFavoriteRepository.GetAllForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind?>(), Arg.Any<PaginationDataDto?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(page));
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<FavoriteItemResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Data.Count);
|
||||
Assert.Equal(2, result.Value.CurrentPage);
|
||||
Assert.Equal(5, result.Value.PerPage);
|
||||
Assert.Equal(12, result.Value.Count);
|
||||
Assert.Equal(3, result.Value.NumberOfPages);
|
||||
Assert.All(result.Value.Data, item =>
|
||||
{
|
||||
Assert.False(item.IsAvailable);
|
||||
Assert.Equal(Guid.Empty, item.LibraryId);
|
||||
Assert.Equal(string.Empty, item.Title);
|
||||
Assert.Equal(Guid.Empty, item.CollectionId);
|
||||
Assert.Equal(string.Empty, item.CollectionTitle);
|
||||
Assert.Equal(Guid.Empty, item.CreatorId);
|
||||
Assert.Equal(string.Empty, item.CreatorName);
|
||||
Assert.Null(item.CoverPath);
|
||||
});
|
||||
Assert.Equal<Guid>([firstItem.Favorite.MediaItemId, secondItem.Favorite.MediaItemId], result.Value.Data.Select(item => item.MediaItemId));
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheItemsHaveDisplayData_ShouldMapEveryDisplayFieldAndPreserveThePaginationMetadata()
|
||||
{
|
||||
// Arrange
|
||||
FavoriteEntity favorite = _favoriteEntityFixture.Create(mediaKind: FavoriteMediaKind.MusicTrack);
|
||||
FavoriteItemDisplayDto display = _favoriteItemDisplayDtoFixture.Create();
|
||||
FavoriteItemDto item = _favoriteItemDtoFixture.Create(favorite: favorite, display: display);
|
||||
PaginatedResultDto<FavoriteItemDto> page = _paginatedResultDtoFixture.Create(
|
||||
data: [item],
|
||||
currentPage: 4,
|
||||
perPage: 10,
|
||||
count: 31,
|
||||
numberOfPages: 4);
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create();
|
||||
_mockFavoriteRepository.GetAllForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind?>(), Arg.Any<PaginationDataDto?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(page));
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<FavoriteItemResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
FavoriteItemResponse response = Assert.Single(result.Value.Data);
|
||||
Assert.Equal(favorite.MediaKind, response.MediaKind);
|
||||
Assert.Equal(favorite.MediaItemId, response.MediaItemId);
|
||||
Assert.True(response.IsAvailable);
|
||||
Assert.Equal(display.LibraryId, response.LibraryId);
|
||||
Assert.Equal(display.Title, response.Title);
|
||||
Assert.Equal(display.CollectionId, response.CollectionId);
|
||||
Assert.Equal(display.CollectionTitle, response.CollectionTitle);
|
||||
Assert.Equal(display.CreatorId, response.CreatorId);
|
||||
Assert.Equal(display.CreatorName, response.CreatorName);
|
||||
Assert.Equal(display.CoverPath, response.CoverPath);
|
||||
Assert.Equal(4, result.Value.CurrentPage);
|
||||
Assert.Equal(10, result.Value.PerPage);
|
||||
Assert.Equal(31, result.Value.Count);
|
||||
Assert.Equal(4, result.Value.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSeveralItemsShareOneLibrary_ShouldEvaluateTheLibraryPolicyOnceForThatLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid sharedLibraryId = Guid.NewGuid();
|
||||
FavoriteItemDto firstItem = _favoriteItemDtoFixture.Create(
|
||||
display: _favoriteItemDisplayDtoFixture.Create(libraryId: sharedLibraryId));
|
||||
FavoriteItemDto secondItem = _favoriteItemDtoFixture.Create(
|
||||
display: _favoriteItemDisplayDtoFixture.Create(libraryId: sharedLibraryId));
|
||||
PaginatedResultDto<FavoriteItemDto> page = _paginatedResultDtoFixture.Create(data: [firstItem, secondItem]);
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create();
|
||||
_mockFavoriteRepository.GetAllForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind?>(), Arg.Any<PaginationDataDto?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(page));
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<FavoriteItemResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId,
|
||||
Arg.Is<PolicyContext>(context => context is LibraryOwnershipPolicyContext && ((LibraryOwnershipPolicyContext)context).LibraryId == sharedLibraryId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenOneLibraryIsDenied_ShouldKeepItsRowsWithoutDisplayDataAndLeaveTheAccessibleRowsUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
Guid accessibleLibraryId = Guid.NewGuid();
|
||||
Guid deniedLibraryId = Guid.NewGuid();
|
||||
FavoriteItemDisplayDto accessibleDisplay = _favoriteItemDisplayDtoFixture.Create(libraryId: accessibleLibraryId);
|
||||
FavoriteItemDto accessibleItem = _favoriteItemDtoFixture.Create(display: accessibleDisplay);
|
||||
FavoriteItemDisplayDto deniedDisplay = _favoriteItemDisplayDtoFixture.Create(libraryId: deniedLibraryId, title: "denied title");
|
||||
FavoriteItemDto deniedItem = _favoriteItemDtoFixture.Create(display: deniedDisplay);
|
||||
FavoriteItemDto itemWithoutDisplay = _favoriteItemDtoFixture.Create(includeDisplay: false);
|
||||
PaginatedResultDto<FavoriteItemDto> page = _paginatedResultDtoFixture.Create(
|
||||
data: [accessibleItem, deniedItem, itemWithoutDisplay]);
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create();
|
||||
_mockFavoriteRepository.GetAllForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind?>(), Arg.Any<PaginationDataDto?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(page));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId,
|
||||
Arg.Is<PolicyContext>(context => context is LibraryOwnershipPolicyContext && ((LibraryOwnershipPolicyContext)context).LibraryId == deniedLibraryId),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResponse<FavoriteItemResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Data.Count);
|
||||
Assert.Collection(
|
||||
result.Value.Data,
|
||||
item =>
|
||||
{
|
||||
Assert.True(item.IsAvailable);
|
||||
Assert.Equal(accessibleDisplay.Title, item.Title);
|
||||
Assert.Equal(accessibleDisplay.LibraryId, item.LibraryId);
|
||||
},
|
||||
item =>
|
||||
{
|
||||
Assert.False(item.IsAvailable);
|
||||
Assert.Equal(Guid.Empty, item.LibraryId);
|
||||
Assert.Equal(string.Empty, item.Title);
|
||||
Assert.Null(item.CoverPath);
|
||||
},
|
||||
item =>
|
||||
{
|
||||
Assert.False(item.IsAvailable);
|
||||
Assert.Equal(Guid.Empty, item.LibraryId);
|
||||
Assert.Equal(string.Empty, item.Title);
|
||||
});
|
||||
Assert.Equal(deniedItem.Favorite.MediaItemId, result.Value.Data[1].MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenNoRowHasDisplayData_ShouldNotEvaluateAnyLibraryPolicy()
|
||||
{
|
||||
// Arrange
|
||||
PaginatedResultDto<FavoriteItemDto> page = _paginatedResultDtoFixture.Create(
|
||||
data: [_favoriteItemDtoFixture.Create(includeDisplay: false)]);
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create();
|
||||
_mockFavoriteRepository.GetAllForUserAsync(Arg.Any<Guid>(), Arg.Any<FavoriteMediaKind?>(), Arg.Any<PaginationDataDto?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(page));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<PolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldPassTheCurrentUserTheMediaKindAndThePaginationDataToTheRepositoryAndForwardTheCancellationToken()
|
||||
{
|
||||
// Arrange
|
||||
PaginationDataDto paginationData = new() { CurrentPage = 3, PerPage = 15 };
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create(
|
||||
mediaKind: FavoriteMediaKind.Book,
|
||||
paginationData: paginationData);
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockFavoriteRepository.Received(1).GetAllForUserAsync(
|
||||
_userId,
|
||||
FavoriteMediaKind.Book,
|
||||
Arg.Is<PaginationDataDto>(data => ReferenceEquals(data, paginationData)),
|
||||
Arg.Any<bool>(),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
using Lumina.Application.Fixtures.Core.Favorites.Queries.GetFavorites;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Favorites.Queries.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetFavoritesQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesQueryValidatorTests
|
||||
{
|
||||
private readonly GetFavoritesQueryValidator _validator = new();
|
||||
private readonly GetFavoritesQueryFixture _getFavoritesQueryFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNotSupplied_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsUndefined_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create(mediaKind: (FavoriteMediaKind)int.MaxValue);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNone_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create(mediaKind: FavoriteMediaKind.None);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(FavoriteMediaKind.MusicArtist)] // A catalogued music kind.
|
||||
[InlineData(FavoriteMediaKind.MusicAlbum)] // A catalogued music kind.
|
||||
[InlineData(FavoriteMediaKind.MusicTrack)] // A catalogued music kind.
|
||||
[InlineData(FavoriteMediaKind.Book)] // A catalogued written content kind.
|
||||
[InlineData(FavoriteMediaKind.Video)] // A planned kind is still a defined enumeration member.
|
||||
[InlineData(FavoriteMediaKind.Photo)] // A planned kind is still a defined enumeration member.
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
GetFavoritesQuery query = _getFavoritesQueryFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user