Refactors the update book slice across the stack

This commit is contained in:
BinaryAlley committed 2026-09-12 12:13:18 -07:00
1 parent 9a71a6d32b
commit 001146eefc
27 files changed
+4065 -632

No files matched your search

@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
@@ -12,7 +12,10 @@ using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Boo
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
@@ -45,11 +48,15 @@ public class UpdateBookCommandHandlerTests
private readonly IValidator<UpdateBookCommand> _mockValidator;
private readonly UpdateBookCommandHandler _sut;
private readonly Guid _userId;
private static readonly Error s_findOrCreateError = Error.Validation("MediaContributor.FindOrCreate", "Could not find or create the media contributor.");
private readonly UpdateBookCommandFixture _commandBookFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCommandHandlerTests"/> class.
@@ -59,6 +66,7 @@ public class UpdateBookCommandHandlerTests
_mockBookRepository = Substitute.For<IBookRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
@@ -72,10 +80,22 @@ public class UpdateBookCommandHandlerTests
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<UpdateBookCommand>()).Returns([]);
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_mediaContributorEntityFixture.Create()));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Default stub: every referenced media contributor already exists.
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
IReadOnlyCollection<Guid> contributorIds = callInfo.Arg<IReadOnlyCollection<Guid>>();
return Result.From<IReadOnlyList<MediaContributorEntity>>([.. contributorIds.Select(contributorId => new MediaContributorEntity
{
Id = contributorId,
DisplayName = contributorId.ToString(),
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
})]);
});
_sut = new UpdateBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
@@ -85,18 +105,25 @@ public class UpdateBookCommandHandlerTests
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
BookEntity? updatedBook = null;
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From<BookEntity?>(callInfo.ArgAt<bool>(2) ? existingBook : updatedBook));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
updatedBook = callInfo.Arg<BookEntity>();
return Result.Updated;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(command.Id, result.Value.Id);
Assert.Equal(Guid.Parse(command.BookId!), result.Value.Id);
Assert.Equal(command.Metadata!.Title, result.Value.Metadata!.Title);
Assert.Equal(command.Contributors, result.Value.Contributors);
Assert.Equal(command.Contributors!.Count, result.Value.Contributors!.Count);
await _mockBookRepository.Received(1).UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -114,7 +141,7 @@ public class UpdateBookCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -131,7 +158,7 @@ public class UpdateBookCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
@@ -139,7 +166,7 @@ public class UpdateBookCommandHandlerTests
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
// Act
@@ -157,7 +184,7 @@ public class UpdateBookCommandHandlerTests
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
@@ -174,8 +201,8 @@ public class UpdateBookCommandHandlerTests
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
@@ -192,34 +219,13 @@ public class UpdateBookCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorFindOrCreateFails_ShouldReturnFailureResultWithoutSaving()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(s_findOrCreateError);
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(s_findOrCreateError, result.FirstError);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRepositoryUpdateFails_ShouldReturnFailureResultWithoutSaving()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Errors.WrittenContent.BookNotFound);
@@ -234,22 +240,21 @@ public class UpdateBookCommandHandlerTests
}
[Fact]
public async Task HandleAsync_WhenContributorsShareTheSameDisplayName_ShouldResolveContributorOnceAndLinkEveryRole()
public async Task HandleAsync_WhenContributorsHaveTheSameIdAndRole_ShouldLinkThemOnce()
{
// Arrange
Guid contributorId = Guid.NewGuid();
UpdateBookCommand command = _commandBookFixture.Create(
contributors:
[
_mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author),
_mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator)
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator)
]);
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(contributor));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
BookEntity? updatedEntity = null;
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From<BookEntity?>(callInfo.ArgAt<bool>(2) ? existingBook : updatedEntity));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
@@ -262,34 +267,30 @@ public class UpdateBookCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync(
"John Doe", "John Smith Doe", Arg.Any<CancellationToken>());
Assert.NotNull(updatedEntity);
Assert.Equal(2, updatedEntity!.BookContributors.Count);
Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributor.Id, linkedContributor.MediaContributorId));
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "author");
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "illustrator");
Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorsHaveDistinctDisplayNames_ShouldResolveEachContributorOnce()
public async Task HandleAsync_WhenContributorsHaveDistinctIds_ShouldLinkEachContributor()
{
// Arrange
Guid firstContributorId = Guid.NewGuid();
Guid secondContributorId = Guid.NewGuid();
UpdateBookCommand command = _commandBookFixture.Create(
contributors:
[
_mediaContributorDtoFixture.Create(displayName: "Author One", legalName: "Author One Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author),
_mediaContributorDtoFixture.Create(displayName: "Author Two", legalName: "Author Two Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator)
_mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Author),
_mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Illustrator)
]);
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create();
MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create();
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From(callInfo.ArgAt<string>(0) == "Author One" ? firstContributor : secondContributor));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
BookEntity? updatedEntity = null;
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From<BookEntity?>(callInfo.ArgAt<bool>(2) ? existingBook : updatedEntity));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
@@ -302,14 +303,10 @@ public class UpdateBookCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync(
"Author One", "Author One Legal", Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync(
"Author Two", "Author Two Legal", Arg.Any<CancellationToken>());
Assert.NotNull(updatedEntity);
Assert.Equal(2, updatedEntity!.BookContributors.Count);
Assert.Equal(firstContributor.Id, updatedEntity.BookContributors[0].MediaContributorId);
Assert.Equal(secondContributor.Id, updatedEntity.BookContributors[1].MediaContributorId);
Assert.Equal(firstContributorId, updatedEntity.BookContributors[0].MediaContributorId);
Assert.Equal(secondContributorId, updatedEntity.BookContributors[1].MediaContributorId);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -318,7 +315,7 @@ public class UpdateBookCommandHandlerTests
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
existingBook.MetadataStatus = MetadataStatus.Enriched;
existingBook.LastMetadataUpdateUtc = new DateTime(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc);
existingBook.MetadataProvider = "TestProvider";
@@ -334,10 +331,15 @@ public class UpdateBookCommandHandlerTests
CreatedBy = Guid.NewGuid(),
UpdatedBy = null
});
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
BookEntity? updatedBook = null;
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Result.From<BookEntity?>(callInfo.ArgAt<bool>(2) ? existingBook : updatedBook));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
.Returns(callInfo =>
{
updatedBook = callInfo.Arg<BookEntity>();
return Result.Updated;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -349,4 +351,145 @@ public class UpdateBookCommandHandlerTests
Assert.Equal(existingBook.MetadataProvider, result.Value.MetadataProvider);
Assert.Equal("/media/covers/cover.jpg", result.Value.CoverPath);
}
[Fact]
public async Task HandleAsync_WhenCalledWithInvalidIsbn_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]);
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.WrittenContent.InvalidIsbn13Format.Description);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)]);
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueMustBePositive.Description);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")]));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")]));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.TagNameCannotBeEmpty.Description);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(
originalReleaseDate: new DateOnly(2025, 1, 1),
originalReleaseYear: 2025,
reReleaseDate: new DateOnly(2024, 1, 1),
reReleaseYear: 2024)));
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([]));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError);
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
// The stored book belongs to a different library than the one named by the route.
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.NewGuid());
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}