Adds book editing tests and parameterizes the shared test fixtures

This commit is contained in:
BinaryAlley committed 2026-09-06 09:37:55 -07:00
1 parent 1bfa07ba5d
commit 145185d715
354 files changed
+7118 -1743

No files matched your search

@@ -1,24 +1,34 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.Setup;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
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;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
@@ -32,6 +42,10 @@ public class AddBookCommandHandlerTests
private readonly IFixture _fixture;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly IMediaContributorRepository _mockMediaContributorRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly Guid _userId;
private readonly AddBookCommandHandler _sut;
private readonly AddBookCommandFixture _commandBookFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
@@ -40,6 +54,9 @@ public class AddBookCommandHandlerTests
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="AddBookCommandHandlerTests"/> class.
@@ -52,13 +69,24 @@ public class AddBookCommandHandlerTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_userId = Guid.NewGuid();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_mediaContributorEntityFixture.Create()));
// Default stubs: the current user is authenticated and the library ownership policy allows access.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
IValidator<AddBookCommand> mockValidator = Substitute.For<IValidator<AddBookCommand>>();
mockValidator.Validate(Arg.Any<AddBookCommand>())
.Returns([]);
_sut = new AddBookCommandHandler(_mockUnitOfWork, mockValidator);
_sut = new AddBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, mockValidator);
}
[Fact]
@@ -103,8 +131,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenCalledWithInvalidISBN_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with { ISBNs = [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)] };
AddBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]);
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
@@ -113,6 +140,7 @@ public class AddBookCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, e => e.Description == Errors.WrittenContent.InvalidIsbn13Format.Description);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -120,8 +148,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with { Ratings = [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)] };
AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)]);
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
@@ -130,6 +157,7 @@ public class AddBookCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.RatingValueMustBePositive.Description);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -137,14 +165,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata! with
{
Genres = [_genreDtoFixture.Create(name: "")]
}
};
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")]));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
@@ -153,6 +174,7 @@ public class AddBookCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -160,14 +182,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata! with
{
Tags = [_tagDtoFixture.Create(name: "")]
}
};
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")]));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
@@ -176,6 +191,7 @@ public class AddBookCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.TagNameCannotBeEmpty.Description);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -183,16 +199,11 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata! with
{
ReleaseInfo = _releaseInfoDtoFixture.Create(
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(
originalReleaseDate: new DateOnly(2025, 1, 1),
reReleaseDate: new DateOnly(2024, 1, 1))
}
};
originalReleaseYear: 2025,
reReleaseDate: new DateOnly(2024, 1, 1),
reReleaseYear: 2024)));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
@@ -201,6 +212,7 @@ public class AddBookCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -208,14 +220,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenLanguageInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata! with
{
Language = _languageInfoDtoFixture.Create(languageCode: "", languageName: "English")
}
};
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: "", languageName: "English")));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
@@ -224,6 +229,7 @@ public class AddBookCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -231,14 +237,7 @@ public class AddBookCommandHandlerTests
public async Task HandleAsync_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
bookCommand = bookCommand with
{
Metadata = bookCommand.Metadata! with
{
OriginalLanguage = _languageInfoDtoFixture.Create(languageCode: "", languageName: "English")
}
};
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: "", languageName: "English")));
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
@@ -247,6 +246,194 @@ public class AddBookCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorsAreLinked_ShouldAttachBookContributorRowsAndReturnThemInTheResponse()
{
// Arrange
AddBookCommand bookCommand = _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)
]);
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? insertedEntity = null;
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
insertedEntity = callInfo.Arg<BookEntity>();
return Result.Created;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(bookCommand.Contributors, result.Value.Contributors);
Assert.NotNull(insertedEntity);
Assert.Equal(2, insertedEntity!.BookContributors.Count);
Assert.Equal(firstContributor.Id, insertedEntity.BookContributors[0].MediaContributorId);
Assert.Equal("author", insertedEntity.BookContributors[0].RoleName);
Assert.Equal(MediaContributorRoleCategory.Author, insertedEntity.BookContributors[0].RoleCategory);
Assert.Equal(secondContributor.Id, insertedEntity.BookContributors[1].MediaContributorId);
Assert.Equal("illustrator", insertedEntity.BookContributors[1].RoleName);
Assert.Equal(MediaContributorRoleCategory.Illustrator, insertedEntity.BookContributors[1].RoleCategory);
await _mockBookRepository.Received(1).InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorsShareTheSameDisplayName_ShouldResolveContributorOnceAndLinkEveryRole()
{
// Arrange
AddBookCommand bookCommand = _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)
]);
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(contributor));
BookEntity? insertedEntity = null;
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
insertedEntity = callInfo.Arg<BookEntity>();
return Result.Created;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync(
"John Doe", "John Smith Doe", Arg.Any<CancellationToken>());
Assert.NotNull(insertedEntity);
Assert.Equal(2, insertedEntity!.BookContributors.Count);
Assert.All(insertedEntity.BookContributors, linkedContributor => Assert.Equal(contributor.Id, linkedContributor.MediaContributorId));
Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "author");
Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "illustrator");
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorHasNullDisplayName_ShouldSkipIt()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors:
[
_mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author),
_mediaContributorDtoFixture.Create(includeName: false, roleName: "unknown", roleCategory: MediaContributorRoleCategory.Other)
]);
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(contributor));
BookEntity? insertedEntity = null;
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
insertedEntity = callInfo.Arg<BookEntity>();
return Result.Created;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync(
"John Doe", "John Smith Doe", Arg.Any<CancellationToken>());
Assert.NotNull(insertedEntity);
Assert.Single(insertedEntity!.BookContributors);
Assert.Equal(contributor.Id, insertedEntity.BookContributors[0].MediaContributorId);
}
[Fact]
public async Task HandleAsync_WhenContributorFindOrCreateFails_ShouldReturnFailureResultWithoutInserting()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
Error findOrCreateError = Error.Validation("MediaContributor.FindOrCreate", "Could not find or create the media contributor.");
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(findOrCreateError);
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(findOrCreateError, result.FirstError);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == bookCommand.LibraryId), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCalledWithValidCommand_ShouldStampTheCurrentUserAsTheAuditActor()
{
// Arrange
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create()]);
BookEntity? insertedEntity = null;
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
insertedEntity = callInfo.Arg<BookEntity>();
return Result.Created;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(insertedEntity);
Assert.Equal(_userId, insertedEntity!.CreatedBy);
Assert.NotEmpty(insertedEntity.BookContributors);
Assert.All(insertedEntity.BookContributors, contributor => Assert.Equal(_userId, contributor.CreatedBy));
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,352 @@
#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;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
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.MediaContributors;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
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;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
/// <summary>
/// Contains unit tests for the <see cref="UpdateBookCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly IMediaContributorRepository _mockMediaContributorRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
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();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCommandHandlerTests"/> class.
/// </summary>
public UpdateBookCommandHandlerTests()
{
_mockBookRepository = Substitute.For<IBookRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<UpdateBookCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated, the library ownership policy allows access,
// the validator passes and the existing book is found in the repository.
_mockCurrentUserService.UserId.Returns(_userId);
_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);
_sut = new UpdateBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCommandIsValid_ShouldUpdateBookAndReturnResponse()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(command.Id, result.Value.Id);
Assert.Equal(command.Metadata!.Title, result.Value.Metadata!.Title);
Assert.Equal(command.Contributors, result.Value.Contributors);
await _mockBookRepository.Received(1).UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutUpdating()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
_mockValidator.Validate(Arg.Any<UpdateBookCommand>()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]);
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
// 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 _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutUpdating()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == existingBook.LibraryId), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
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>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Errors.WrittenContent.BookNotFound);
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorsShareTheSameDisplayName_ShouldResolveContributorOnceAndLinkEveryRole()
{
// Arrange
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)
]);
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? updatedEntity = null;
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
updatedEntity = callInfo.Arg<BookEntity>();
return Result.Updated;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// 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");
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenContributorsHaveDistinctDisplayNames_ShouldResolveEachContributorOnce()
{
// Arrange
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)
]);
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? updatedEntity = null;
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(callInfo =>
{
updatedEntity = callInfo.Arg<BookEntity>();
return Result.Updated;
});
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// 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);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenStoredBookHasEnrichmentAndCover_ShouldPreserveThemInTheResponse()
{
// Arrange
UpdateBookCommand command = _commandBookFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.Id);
existingBook.MetadataStatus = MetadataStatus.Enriched;
existingBook.LastMetadataUpdateUtc = new DateTime(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc);
existingBook.MetadataProvider = "TestProvider";
existingBook.BookArtwork.Add(new BookArtworkEntity
{
Id = Guid.NewGuid(),
BookId = existingBook.Id,
ArtworkType = ArtworkType.Cover,
Ordinal = 0,
FileName = "/media/covers/cover.jpg",
Status = ArtworkStatus.Enriched,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedBy = null
});
_mockBookRepository.GetByIdAsync(command.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(MetadataStatus.Enriched, result.Value.MetadataStatus);
Assert.Equal(existingBook.LastMetadataUpdateUtc, result.Value.LastMetadataUpdateUtc);
Assert.Equal(existingBook.MetadataProvider, result.Value.MetadataProvider);
Assert.Equal("/media/covers/cover.jpg", result.Value.CoverPath);
}
}
@@ -0,0 +1,398 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
using Lumina.Application.UnitTests.Common.Setup;
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.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
/// <summary>
/// Contains unit tests for the <see cref="UpdateBookCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookCommandValidatorTests
{
private readonly UpdateBookCommandFixture _commandBookFixture = new();
private readonly UpdateBookCommandValidator _validator = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create();
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(id: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenMetadataIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(includeMetadata: false);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull);
}
[Fact]
public void Validate_WhenTitleIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTitle: false));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty);
}
[Fact]
public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(300)));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong);
}
[Fact]
public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeReleaseInfo: false));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull);
}
[Fact]
public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
}
[Fact]
public void Validate_WhenGenresIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeGenres: false));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull);
}
[Fact]
public void Validate_WhenTagsIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeTags: false));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull);
}
[Fact]
public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty);
}
[Fact]
public void Validate_WhenFormatIsInvalid_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(format: (BookFormat)99);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.UnknownBookFormat);
}
[Fact]
public void Validate_WhenEditionExceeds50Characters_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(edition: new Faker().Random.String2(51));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong);
}
[Fact]
public void Validate_WhenVolumeNumberIsNegative_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: -1);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero);
}
[Fact]
public void Validate_WhenAsinIsNotTenCharacters_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(asin: new Faker().Random.String2(9));
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong);
}
[Fact]
public void Validate_WhenGoodreadsIdIsNonNumeric_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "abc123");
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric);
}
[Fact]
public void Validate_WhenLccnHasInvalidFormat_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: "invalid123");
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.InvalidLccnFormat);
}
[Fact]
public void Validate_WhenOclcNumberHasInvalidFormat_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "invalid_oclc_number");
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOclcFormat);
}
[Fact]
public void Validate_WhenOpenLibraryIdHasInvalidFormat_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "InvalidID");
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId);
}
[Fact]
public void Validate_WhenGoogleBooksIdHasInvalidFormat_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: "invalid!");
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong);
}
[Fact]
public void Validate_WhenBarnesAndNobleIdIsNotTenDigits_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: "abc123");
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong);
}
[Fact]
public void Validate_WhenAppleBooksIdHasInvalidFormat_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "395211");
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.InvalidAppleBooksIdFormat);
}
[Fact]
public void Validate_WhenIsbnsIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.IsbnListCannotBeNull);
}
[Fact]
public void Validate_WhenIsbnValueIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.IsbnValueCannotBeEmpty);
}
[Fact]
public void Validate_WhenIsbn13ValueIsInvalid_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.InvalidIsbn13Format);
}
[Fact]
public void Validate_WhenContributorsIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
}
[Fact]
public void Validate_WhenContributorDisplayNameIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty);
}
[Fact]
public void Validate_WhenRatingsIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull);
}
[Fact]
public void Validate_WhenRatingValueIsNegative_ShouldHaveValidationError()
{
// Arrange
UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1)]);
// Act
List<Error> result = _validator.TestValidate(bookCommand);
// Assert
result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive);
}
}
@@ -0,0 +1,336 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
/// <summary>
/// Contains unit tests for the <see cref="UpdateBookCoverCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookCoverCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMediaContributorRepository _mockMediaContributorRepository;
private readonly IBookArtworkService _mockBookArtworkService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<UpdateBookCoverCommand> _mockValidator;
private readonly UpdateBookCoverCommandHandler _sut;
private readonly Guid _userId;
private readonly UpdateBookCoverCommandFixture _commandFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCoverCommandHandlerTests"/> class.
/// </summary>
public UpdateBookCoverCommandHandlerTests()
{
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<UpdateBookCoverCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated, the library ownership policy allows access,
// the validator passes and the artwork storage succeeds.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<UpdateBookCoverCommand>()).Returns([]);
_mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.From("/media/books/cover.jpg"));
_sut = new UpdateBookCoverCommandHandler(_mockUnitOfWork, _mockBookArtworkService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenBookHasNoExistingCover_ShouldStoreArtworkAndAddCoverArtwork()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
existingBook.BookArtwork = [];
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("/media/books/cover.jpg", result.Value);
Assert.Single(existingBook.BookArtwork);
Assert.Equal(ArtworkType.Cover, existingBook.BookArtwork[0].ArtworkType);
Assert.Equal(result.Value, existingBook.BookArtwork[0].FileName);
Assert.Equal(ArtworkStatus.Enriched, existingBook.BookArtwork[0].Status);
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(
existingBook.LibraryId,
existingBook.Id,
library.Title,
string.Empty,
existingBook.Title,
Arg.Any<System.IO.Stream>(),
Arg.Any<string>(),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookHasExistingCover_ShouldReplaceTheStoredCoverFile()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: command.BookId, artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg");
existingBook.BookArtwork = [existingCover];
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("/media/books/cover.jpg", result.Value);
Assert.Single(existingBook.BookArtwork);
Assert.Equal(result.Value, existingCover.FileName);
Assert.Equal(ArtworkStatus.Enriched, existingCover.Status);
Assert.Equal(_userId, existingCover.UpdatedBy);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookHasAuthorContributors_ShouldPassTheResolvedAuthorNameToArtworkService()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "J.R.R. Tolkien");
MediaContributorEntity illustrator = _mediaContributorEntityFixture.Create(displayName: "Alan Lee");
existingBook.BookContributors =
[
_bookContributorEntityFixture.Create(bookId: command.BookId, mediaContributorId: author.Id, roleCategory: MediaContributorRoleCategory.Author),
_bookContributorEntityFixture.Create(bookId: command.BookId, mediaContributorId: illustrator.Id, roleCategory: MediaContributorRoleCategory.Illustrator)
];
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([author, illustrator]));
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(
existingBook.LibraryId,
existingBook.Id,
library.Title,
"J.R.R. Tolkien",
existingBook.Title,
Arg.Any<System.IO.Stream>(),
Arg.Any<string>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAuthorResolutionFails_ShouldStoreArtworkWithEmptyAuthorName()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
existingBook.BookContributors =
[
_bookContributorEntityFixture.Create(bookId: command.BookId, roleCategory: MediaContributorRoleCategory.Author)
];
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(
existingBook.LibraryId,
existingBook.Id,
library.Title,
string.Empty,
existingBook.Title,
Arg.Any<System.IO.Stream>(),
Arg.Any<string>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutStoringArtwork()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
_mockValidator.Validate(Arg.Any<UpdateBookCoverCommand>()).Returns([Errors.WrittenContent.BookCoverCannotBeNull]);
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookCoverCannotBeNull, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutStoringArtwork()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkStorageFails_ShouldReturnFailureResultWithoutSaving()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(existingBook));
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Errors.FileSystemManagement.FileTooLarge);
// Act
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
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.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
/// <summary>
/// Contains unit tests for the <see cref="UpdateBookCoverCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookCoverCommandValidatorTests
{
private readonly UpdateBookCoverCommandFixture _commandFixture = new();
private readonly UpdateBookCoverCommandValidator _validator = new();
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCoverIsNull_ShouldHaveValidationError()
{
// Arrange
UpdateBookCoverCommand command = _commandFixture.Create(includeCover: false);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookCoverCannotBeNull);
}
}
@@ -0,0 +1,209 @@
#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;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
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.Queries.GetBook;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
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;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
/// <summary>
/// Contains unit tests for the <see cref="GetBookQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBookQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly IMediaContributorRepository _mockMediaContributorRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetBookQuery> _mockValidator;
private readonly GetBookQueryHandler _sut;
private readonly Guid _userId;
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
private readonly GetBookQueryFixture _getBookQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetBookQueryHandlerTests"/> class.
/// </summary>
public GetBookQueryHandlerTests()
{
_mockBookRepository = Substitute.For<IBookRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetBookQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated and the library ownership policy allows access.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetBookQuery>()).Returns([]);
_sut = new GetBookQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenBookExistsWithoutContributors_ShouldReturnMappedBookResponse()
{
// Arrange
GetBookQuery query = _getBookQueryFixture.Create();
BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id);
_mockBookRepository.GetByIdAsync(query.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(bookEntity));
// Act
Result<BookResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(query.Id, result.Value.Id);
Assert.Equal(bookEntity.Title, result.Value.Metadata!.Title);
Assert.Null(result.Value.Contributors);
await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenBookHasContributors_ShouldReturnResponseWithResolvedContributorNames()
{
// Arrange
GetBookQuery query = _getBookQueryFixture.Create();
BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id);
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
bookEntity.BookContributors =
[
_bookContributorEntityFixture.Create(bookId: query.Id, mediaContributorId: contributor.Id, roleName: "author", roleCategory: MediaContributorRoleCategory.Author)
];
_mockBookRepository.GetByIdAsync(query.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(bookEntity));
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([contributor]));
// Act
Result<BookResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value.Contributors);
Assert.Single(result.Value.Contributors!);
Assert.Equal(contributor.DisplayName, result.Value.Contributors![0].Name!.DisplayName);
Assert.Equal("author", result.Value.Contributors![0].Role!.Name);
}
[Fact]
public async Task HandleAsync_WhenBookNotFound_ShouldReturnBookNotFoundError()
{
// Arrange
GetBookQuery query = _getBookQueryFixture.Create();
_mockBookRepository.GetByIdAsync(query.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
// Act
Result<BookResponse> result = await _sut.HandleAsync(query, 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>());
}
[Fact]
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
{
// Arrange
GetBookQuery query = _getBookQueryFixture.Create();
_mockBookRepository.GetByIdAsync(query.Id, Arg.Any<CancellationToken>())
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
// Act
Result<BookResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetBookQuery query = _getBookQueryFixture.Create();
BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id);
_mockBookRepository.GetByIdAsync(query.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(bookEntity));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<BookResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == bookEntity.LibraryId), Arg.Any<CancellationToken>());
await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetBookQuery query = _getBookQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<BookResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
{
// Arrange
GetBookQuery query = _getBookQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetBookQuery>()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]);
// Act
Result<BookResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
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.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
/// <summary>
/// Contains unit tests for the <see cref="GetBookQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBookQueryValidatorTests
{
private readonly GetBookQueryFixture _queryBookFixture = new();
private readonly GetBookQueryValidator _validator = new();
[Fact]
public void Validate_WhenIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetBookQuery query = _queryBookFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetBookQuery query = _queryBookFixture.Create(id: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
}
}
@@ -24,8 +24,7 @@ public class GetBooksQueryValidatorTests
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetBooksQuery query = _getBooksQueryFixture.Create();
query = query with { Filter = query.Filter with { LibraryId = Guid.Empty } };
GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
@@ -24,8 +24,7 @@ public class GetBooksLiteQueryValidatorTests
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
query = query with { Filter = query.Filter with { LibraryId = Guid.Empty } };
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(query);
@@ -51,8 +50,7 @@ public class GetBooksLiteQueryValidatorTests
public void Validate_WhenFilterAlphaKeyIsNotASingleLetterOrSpecialKey_ShouldHaveValidationError()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
query = query with { Filter = query.Filter with { FilterAlphaKey = "AB" } };
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(filterAlphaKey: "AB");
// Act
List<Error> result = _validator.TestValidate(query);
@@ -65,8 +63,7 @@ public class GetBooksLiteQueryValidatorTests
public void Validate_WhenFilterAlphaKeyIsASingleLetter_ShouldNotHaveValidationError()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
query = query with { Filter = query.Filter with { FilterAlphaKey = "Q" } };
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(filterAlphaKey: "Q");
// Act
List<Error> result = _validator.TestValidate(query);
@@ -79,8 +76,7 @@ public class GetBooksLiteQueryValidatorTests
public void Validate_WhenFilterAlphaKeyIsNumberOrSymbol_ShouldNotHaveValidationError()
{
// Arrange
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
query = query with { Filter = query.Filter with { FilterAlphaKey = "#" } };
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(filterAlphaKey: "#");
// Act
List<Error> result = _validator.TestValidate(query);