mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 19:11:10 +00:00
Adds book editing tests and parameterizes the shared test fixtures
This commit is contained in:
1 parent
1bfa07ba5d
commit
145185d715
354 files changed
+7118
-1743
No files matched your search
+2
-4
@@ -57,10 +57,8 @@ public class BookMetadataDtoMappingTests
|
||||
Book book = _bookFixture.Create();
|
||||
BookMetadataDto metadata = _bookMetadataDtoFixture.Create(
|
||||
title: "The Fellowship of the Ring",
|
||||
goodreadsId: "3") with
|
||||
{
|
||||
Genres = [_genreDtoFixture.Create(name: "")]
|
||||
};
|
||||
goodreadsId: "3",
|
||||
genres: [_genreDtoFixture.Create(name: "")]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = book.ApplyMetadata(metadata);
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetBookRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBookRequestMappingTests
|
||||
{
|
||||
private readonly GetBookRequestFixture _requestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingRequestWithValidId_ShouldMapIdCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
GetBookRequest request = _requestFixture.Create(id: bookId.ToString());
|
||||
|
||||
// Act
|
||||
GetBookQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(bookId, result.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingRequestWithInvalidId_ShouldMapEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _requestFixture.Create(id: "not-a-guid");
|
||||
|
||||
// Act
|
||||
GetBookQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(Guid.Empty, result.Id);
|
||||
}
|
||||
}
|
||||
+3
-6
@@ -40,8 +40,7 @@ public class GetBooksLiteRequestMappingTests
|
||||
public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
request = request with { CurrentPage = null, PerPage = null };
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetBooksLiteQuery result = request.ToQuery();
|
||||
@@ -56,8 +55,7 @@ public class GetBooksLiteRequestMappingTests
|
||||
public void ToQuery_WhenOnlyPerPageProvided_ShouldDefaultCurrentPageToOne()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
request = request with { CurrentPage = null, PerPage = 25 };
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(perPage: 25, includeCurrentPage: false);
|
||||
|
||||
// Act
|
||||
GetBooksLiteQuery result = request.ToQuery();
|
||||
@@ -72,8 +70,7 @@ public class GetBooksLiteRequestMappingTests
|
||||
public void ToQuery_WhenOnlyCurrentPageProvided_ShouldDefaultPerPageToTwoHundred()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
request = request with { CurrentPage = 3, PerPage = null };
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(currentPage: 3, includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetBooksLiteQuery result = request.ToQuery();
|
||||
|
||||
+3
-6
@@ -40,8 +40,7 @@ public class GetBooksRequestMappingTests
|
||||
public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
request = request with { CurrentPage = null, PerPage = null };
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create(includeCurrentPage: false, includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetBooksQuery result = request.ToQuery();
|
||||
@@ -56,8 +55,7 @@ public class GetBooksRequestMappingTests
|
||||
public void ToQuery_WhenOnlyPerPageProvided_ShouldDefaultCurrentPageToOne()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
request = request with { CurrentPage = null, PerPage = 25 };
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create(perPage: 25, includeCurrentPage: false);
|
||||
|
||||
// Act
|
||||
GetBooksQuery result = request.ToQuery();
|
||||
@@ -72,8 +70,7 @@ public class GetBooksRequestMappingTests
|
||||
public void ToQuery_WhenOnlyCurrentPageProvided_ShouldDefaultPerPageToTwoHundred()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
request = request with { CurrentPage = 3, PerPage = null };
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create(currentPage: 3, includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetBooksQuery result = request.ToQuery();
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateBookCommandMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookCommandMappingTests
|
||||
{
|
||||
private readonly UpdateBookCommandFixture _commandFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToBookMetadataDto_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCommand command = _commandFixture.Create();
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = command.ToBookMetadataDto();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(command.Metadata!.Title, result.Title);
|
||||
Assert.Equal(command.Metadata.OriginalTitle, result.OriginalTitle);
|
||||
Assert.Equal(command.Metadata.Description, result.Description);
|
||||
Assert.Equal(command.Metadata.ReleaseInfo, result.ReleaseInfo);
|
||||
Assert.Equal(command.Metadata.Genres, result.Genres);
|
||||
Assert.Equal(command.Metadata.Tags, result.Tags);
|
||||
Assert.Equal(command.Metadata.Language, result.Language);
|
||||
Assert.Equal(command.Metadata.OriginalLanguage, result.OriginalLanguage);
|
||||
Assert.Equal(command.Metadata.Publisher, result.Publisher);
|
||||
Assert.Equal(command.Metadata.PageCount, result.PageCount);
|
||||
Assert.Equal(command.Format, result.Format);
|
||||
Assert.Equal(command.Edition, result.Edition);
|
||||
Assert.Equal(command.VolumeNumber, result.VolumeNumber);
|
||||
Assert.Equal(command.Series, result.Series);
|
||||
Assert.Equal(command.ASIN, result.ASIN);
|
||||
Assert.Equal(command.GoodreadsId, result.GoodreadsId);
|
||||
Assert.Equal(command.LCCN, result.LCCN);
|
||||
Assert.Equal(command.OCLCNumber, result.OCLCNumber);
|
||||
Assert.Equal(command.OpenLibraryId, result.OpenLibraryId);
|
||||
Assert.Equal(command.LibraryThingId, result.LibraryThingId);
|
||||
Assert.Equal(command.GoogleBooksId, result.GoogleBooksId);
|
||||
Assert.Equal(command.BarnesAndNobleId, result.BarnesAndNobleId);
|
||||
Assert.Equal(command.AppleBooksId, result.AppleBooksId);
|
||||
Assert.Equal(command.ISBNs, result.Isbns);
|
||||
Assert.Equal(command.Contributors, result.Contributors);
|
||||
Assert.Equal(command.Ratings, result.Ratings);
|
||||
Assert.Null(result.CoverImagePath);
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateBookRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookRequestMappingTests
|
||||
{
|
||||
private readonly UpdateBookRequestFixture _requestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _requestFixture.Create(id: bookId);
|
||||
|
||||
// Act
|
||||
UpdateBookCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(bookId, result.Id);
|
||||
Assert.Equal(request.Metadata, result.Metadata);
|
||||
Assert.Equal(request.Format, result.Format);
|
||||
Assert.Equal(request.Edition, result.Edition);
|
||||
Assert.Equal(request.VolumeNumber, result.VolumeNumber);
|
||||
Assert.Equal(request.Series, result.Series);
|
||||
Assert.Equal(request.ASIN, result.ASIN);
|
||||
Assert.Equal(request.GoodreadsId, result.GoodreadsId);
|
||||
Assert.Equal(request.LCCN, result.LCCN);
|
||||
Assert.Equal(request.OCLCNumber, result.OCLCNumber);
|
||||
Assert.Equal(request.OpenLibraryId, result.OpenLibraryId);
|
||||
Assert.Equal(request.LibraryThingId, result.LibraryThingId);
|
||||
Assert.Equal(request.GoogleBooksId, result.GoogleBooksId);
|
||||
Assert.Equal(request.BarnesAndNobleId, result.BarnesAndNobleId);
|
||||
Assert.Equal(request.AppleBooksId, result.AppleBooksId);
|
||||
Assert.Equal(request.ISBNs, result.ISBNs);
|
||||
Assert.Equal(request.Contributors, result.Contributors);
|
||||
Assert.Equal(request.Ratings, result.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _requestFixture.Create(id: bookId, includeOptionalProperties: false);
|
||||
|
||||
// Act
|
||||
UpdateBookCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(bookId, result.Id);
|
||||
Assert.NotNull(result.Metadata);
|
||||
Assert.Equal(request.Metadata, result.Metadata);
|
||||
Assert.Null(result.Format);
|
||||
Assert.Null(result.Edition);
|
||||
Assert.Null(result.VolumeNumber);
|
||||
Assert.Null(result.Series);
|
||||
Assert.Null(result.ASIN);
|
||||
Assert.Null(result.GoodreadsId);
|
||||
Assert.Null(result.LCCN);
|
||||
Assert.Null(result.OCLCNumber);
|
||||
Assert.Null(result.OpenLibraryId);
|
||||
Assert.Null(result.LibraryThingId);
|
||||
Assert.Null(result.GoogleBooksId);
|
||||
Assert.Null(result.BarnesAndNobleId);
|
||||
Assert.Null(result.AppleBooksId);
|
||||
Assert.Null(result.ISBNs);
|
||||
Assert.Null(result.Contributors);
|
||||
Assert.Null(result.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest request = _requestFixture.Create(
|
||||
isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)],
|
||||
contributors:
|
||||
[
|
||||
new(
|
||||
new("John Doe", "John Smith Doe"),
|
||||
new("Author", MediaContributorRoleCategory.Author)
|
||||
)
|
||||
],
|
||||
ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)],
|
||||
includeOptionalProperties: false
|
||||
);
|
||||
|
||||
// Act
|
||||
UpdateBookCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(request.ISBNs, result.ISBNs);
|
||||
Assert.Equal(request.Contributors, result.Contributors);
|
||||
Assert.Equal(request.Ratings, result.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequestWithNullId_ShouldMapEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest request = _requestFixture.Create(includeId: false);
|
||||
|
||||
// Act
|
||||
UpdateBookCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(Guid.Empty, result.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequestWithEmptyId_ShouldMapEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest request = _requestFixture.Create(rawId: string.Empty);
|
||||
|
||||
// Act
|
||||
UpdateBookCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(Guid.Empty, result.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingRequestWithUnparseableId_ShouldMapEmptyGuid()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest request = _requestFixture.Create(rawId: "not-a-guid");
|
||||
|
||||
// Act
|
||||
UpdateBookCommand result = request.ToCommand();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(Guid.Empty, result.Id);
|
||||
}
|
||||
}
|
||||
+233
-46
@@ -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>());
|
||||
}
|
||||
}
|
||||
+142
-281
File diff suppressed because it is too large.
Load diff
+352
@@ -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);
|
||||
}
|
||||
}
|
||||
+398
@@ -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);
|
||||
}
|
||||
}
|
||||
+336
@@ -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>());
|
||||
}
|
||||
}
|
||||
+61
@@ -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);
|
||||
}
|
||||
}
|
||||
+209
@@ -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>());
|
||||
}
|
||||
}
|
||||
+48
@@ -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);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -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);
|
||||
|
||||
+4
-8
@@ -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);
|
||||
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateBookRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookRequestTests
|
||||
{
|
||||
private readonly UpdateBookRequestFixture _updateBookRequestFixture = new();
|
||||
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalled_ShouldReturnValidUpdateBookRequest()
|
||||
{
|
||||
// Act
|
||||
UpdateBookRequest sut = _updateBookRequestFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut);
|
||||
Assert.False(string.IsNullOrWhiteSpace(sut.Id));
|
||||
Assert.NotNull(sut.Metadata);
|
||||
Assert.NotNull(sut.ISBNs);
|
||||
Assert.NotEmpty(sut.ISBNs);
|
||||
Assert.NotNull(sut.Contributors);
|
||||
Assert.NotEmpty(sut.Contributors);
|
||||
Assert.NotNull(sut.Ratings);
|
||||
Assert.NotEmpty(sut.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_WhenSerializingUpdateBookRequest_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest expected = _updateBookRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
UpdateBookRequest? actual = JsonSerializer.Deserialize<UpdateBookRequest>(json, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(actual);
|
||||
Assert.Equivalent(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Serialize_WhenSerializingUpdateBookRequest_ShouldSerializeFormatAsCamelCaseString()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest sut = _updateBookRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(sut, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.Contains("\"Format\":\"", json, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("\"Format\":\"0\"", json, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deconstruct_WhenCalled_ShouldReturnAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest sut = _updateBookRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
(string? id, WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List<IsbnDto>? isbns, List<MediaContributorDto>? contributors, List<BookRatingDto>? ratings) = sut;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(sut.Id, id);
|
||||
Assert.Equal(sut.Metadata, metadata);
|
||||
Assert.Equal(sut.Format, format);
|
||||
Assert.Equal(sut.Edition, edition);
|
||||
Assert.Equal(sut.VolumeNumber, volumeNumber);
|
||||
Assert.Equal(sut.Series, series);
|
||||
Assert.Equal(sut.ASIN, asin);
|
||||
Assert.Equal(sut.GoodreadsId, goodreadsId);
|
||||
Assert.Equal(sut.LCCN, lccn);
|
||||
Assert.Equal(sut.OCLCNumber, oclcNumber);
|
||||
Assert.Equal(sut.OpenLibraryId, openLibraryId);
|
||||
Assert.Equal(sut.LibraryThingId, libraryThingId);
|
||||
Assert.Equal(sut.GoogleBooksId, googleBooksId);
|
||||
Assert.Equal(sut.BarnesAndNobleId, barnesAndNobleId);
|
||||
Assert.Equal(sut.AppleBooksId, appleBooksId);
|
||||
Assert.Equal(sut.ISBNs, isbns);
|
||||
Assert.Equal(sut.Contributors, contributors);
|
||||
Assert.Equal(sut.Ratings, ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest first = _updateBookRequestFixture.Create();
|
||||
UpdateBookRequest second = first with { };
|
||||
|
||||
// Act
|
||||
bool areEqual = first == second;
|
||||
|
||||
// Assert
|
||||
Assert.True(areEqual);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -39,7 +39,7 @@ public class BookLiteResponseTests
|
||||
public void RoundTrip_WhenSerializingBookLiteResponseWithNullValues_ShouldPreserveNulls()
|
||||
{
|
||||
// Arrange
|
||||
BookLiteResponse expected = _bookLiteResponseFixture.Create() with { ReleaseYear = null, CoverPath = null };
|
||||
BookLiteResponse expected = _bookLiteResponseFixture.Create(includeReleaseYear: false, includeCoverPath: false);
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
|
||||
+123
@@ -347,6 +347,129 @@ public class BookRepositoryTests
|
||||
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenChangingIdentityAndEnrichmentColumns_ShouldPreserveTheStoredValues()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity storedBook = _bookEntityFixture.Create();
|
||||
_mockContext.Books.Add(storedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
Guid storedLibraryId = storedBook.LibraryId;
|
||||
string storedPath = storedBook.Path;
|
||||
MetadataStatus storedMetadataStatus = storedBook.MetadataStatus;
|
||||
DateTime? storedLastMetadataUpdateUtc = storedBook.LastMetadataUpdateUtc;
|
||||
string? storedMetadataProvider = storedBook.MetadataProvider;
|
||||
DateTime storedCreatedOnUtc = storedBook.CreatedOnUtc;
|
||||
Guid storedCreatedBy = storedBook.CreatedBy;
|
||||
|
||||
BookEntity data = _bookEntityFixture.Create(id: storedBook.Id);
|
||||
data.Title = "Updated Title";
|
||||
data.LibraryId = Guid.NewGuid();
|
||||
data.Path = "/books/updated.epub";
|
||||
data.MetadataStatus = MetadataStatus.Enriched;
|
||||
data.LastMetadataUpdateUtc = DateTime.UtcNow;
|
||||
data.MetadataProvider = "UpdatedProvider";
|
||||
data.CreatedOnUtc = DateTime.UtcNow.AddYears(-10);
|
||||
data.CreatedBy = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookEntity? retrievedBook = await _mockContext.Books
|
||||
.Include(book => book.Tags)
|
||||
.Include(book => book.Genres)
|
||||
.Include(book => book.ISBNs)
|
||||
.Include(book => book.Ratings)
|
||||
.Include(book => book.BookContributors)
|
||||
.FirstOrDefaultAsync(book => book.Id == storedBook.Id);
|
||||
Assert.NotNull(retrievedBook);
|
||||
Assert.Equal("Updated Title", retrievedBook!.Title);
|
||||
// The identity, enrichment and audit columns of the stored book are never overwritten by an edit.
|
||||
Assert.Equal(storedLibraryId, retrievedBook.LibraryId);
|
||||
Assert.Equal(storedPath, retrievedBook.Path);
|
||||
Assert.Equal(storedMetadataStatus, retrievedBook.MetadataStatus);
|
||||
Assert.Equal(storedLastMetadataUpdateUtc, retrievedBook.LastMetadataUpdateUtc);
|
||||
Assert.Equal(storedMetadataProvider, retrievedBook.MetadataProvider);
|
||||
Assert.Equal(storedCreatedOnUtc, retrievedBook.CreatedOnUtc);
|
||||
Assert.Equal(storedCreatedBy, retrievedBook.CreatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenDataContainsExistingTagAndGenreNames_ShouldReuseTheStoredTagAndGenreEntities()
|
||||
{
|
||||
// Arrange
|
||||
TagEntity existingTag = _tagEntityFixture.Create(name: "ExistingTag");
|
||||
GenreEntity existingGenre = _genreEntityFixture.Create(name: "ExistingGenre");
|
||||
BookEntity storedBook = _bookEntityFixture.Create();
|
||||
storedBook.Tags = [existingTag];
|
||||
storedBook.Genres = [existingGenre];
|
||||
_mockContext.Books.Add(storedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
BookEntity data = _bookEntityFixture.Create(id: storedBook.Id);
|
||||
data.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
|
||||
data.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookEntity? retrievedBook = await _mockContext.Books
|
||||
.Include(book => book.Tags)
|
||||
.Include(book => book.Genres)
|
||||
.FirstOrDefaultAsync(book => book.Id == storedBook.Id);
|
||||
Assert.NotNull(retrievedBook);
|
||||
TagEntity retrievedTag = Assert.Single(retrievedBook!.Tags);
|
||||
GenreEntity retrievedGenre = Assert.Single(retrievedBook.Genres);
|
||||
Assert.Equal("ExistingTag", retrievedTag.Name);
|
||||
Assert.Equal("ExistingGenre", retrievedGenre.Name);
|
||||
// The stored rows of the shared tables are not duplicated by the update.
|
||||
Assert.Single(_mockContext.Set<TagEntity>().Where(tag => tag.Name == "ExistingTag"));
|
||||
Assert.Single(_mockContext.Set<GenreEntity>().Where(genre => genre.Name == "ExistingGenre"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenReplacingOwnedCollections_ShouldReplaceIsbnsRatingsAndBookContributors()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity storedBook = _bookEntityFixture.Create();
|
||||
storedBook.ISBNs = [_isbnEntityFixture.Create(value: "9780395272237", format: IsbnFormat.Isbn13)];
|
||||
storedBook.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)];
|
||||
storedBook.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, roleCategory: MediaContributorRoleCategory.Author)];
|
||||
_mockContext.Books.Add(storedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
BookEntity data = _bookEntityFixture.Create(id: storedBook.Id);
|
||||
data.ISBNs = [_isbnEntityFixture.Create(value: "9780261102693", format: IsbnFormat.Isbn13)];
|
||||
data.Ratings = [_bookRatingEntityFixture.Create(value: 3.5M, maxValue: 5, source: BookRatingSource.Amazon, voteCount: 50)];
|
||||
data.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, mediaContributorId: Guid.NewGuid(), roleCategory: MediaContributorRoleCategory.Illustrator)];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookEntity? retrievedBook = await _mockContext.Books
|
||||
.Include(book => book.ISBNs)
|
||||
.Include(book => book.Ratings)
|
||||
.Include(book => book.BookContributors)
|
||||
.FirstOrDefaultAsync(book => book.Id == storedBook.Id);
|
||||
Assert.NotNull(retrievedBook);
|
||||
IsbnEntity retrievedIsbn = Assert.Single(retrievedBook!.ISBNs);
|
||||
BookRatingEntity retrievedRating = Assert.Single(retrievedBook.Ratings);
|
||||
BookContributorEntity retrievedContributor = Assert.Single(retrievedBook.BookContributors);
|
||||
Assert.Equal("9780261102693", retrievedIsbn.Value);
|
||||
Assert.Equal(3.5M, retrievedRating.Value);
|
||||
Assert.Equal(MediaContributorRoleCategory.Illustrator, retrievedContributor.RoleCategory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedBooks()
|
||||
{
|
||||
|
||||
+42
@@ -224,4 +224,46 @@ public class BookArtworkServiceTests
|
||||
authorName,
|
||||
$"{bookTitle}-{bookId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenUploadedStreamIsNull_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", null!, "cover.jpg", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenUploadedStreamIsEmpty_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream emptyStream = new([]);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", emptyStream, "cover.jpg", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenUploadedStreamExceedsTheMaximumSize_ShouldReturnFileTooLarge()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream oversizedStream = new(new byte[(10 * 1024 * 1024) + 1]);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", oversizedStream, "cover.jpg", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
|
||||
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
|
||||
+121
-4
@@ -1,10 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
@@ -19,20 +25,131 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenConten
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBookEndpointTests
|
||||
{
|
||||
private readonly GetBookEndpoint _sut = Factory.Create<GetBookEndpoint>();
|
||||
private readonly IQueryHandler<GetBookQuery, Result<BookResponse>> _mockHandler;
|
||||
private readonly GetBookEndpoint _sut;
|
||||
private readonly GetBookRequestFixture _getBookRequestFixture = new();
|
||||
private readonly BookResponseFixture _bookResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetBookEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetBookQuery, Result<BookResponse>>>();
|
||||
_sut = Factory.Create<GetBookEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResult()
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookResponse()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create(id: Guid.NewGuid().ToString());
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookResponse expectedResponse = _bookResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<Ok>(result);
|
||||
Ok<BookResponse> okResult = Assert.IsType<Ok<BookResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
|
||||
Assert.Equal("Book.NotFound", problemDetailsBody.Title);
|
||||
Assert.Equal("BookNotFound", problemDetailsBody.Detail);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Error.Validation(description: "BookIdCannotBeEmpty");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetBookQueryToHandler()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
GetBookRequest request = _getBookRequestFixture.Create(id: bookId.ToString());
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetBookQuery>(query => query.Id == bookId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBookQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_bookResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<UpdateBookCommand, Result<BookResponse>> _mockHandler;
|
||||
private readonly UpdateBookEndpoint _sut;
|
||||
private readonly UpdateBookRequestFixture _updateBookRequestFixture = new();
|
||||
private readonly BookResponseFixture _bookResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateBookEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<UpdateBookCommand, Result<BookResponse>>>();
|
||||
_sut = Factory.Create<UpdateBookEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid routeId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookResponse expectedResponse = _bookResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
ConfigureRequest(routeId.ToString());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<BookResponse> okResult = Assert.IsType<Ok<BookResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid routeId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
ConfigureRequest(routeId.ToString());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
|
||||
Assert.Equal("Book.NotFound", problemDetailsBody.Title);
|
||||
Assert.Equal("BookNotFound", problemDetailsBody.Detail);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid routeId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Error.Validation(description: "BookIdCannotBeEmpty");
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
ConfigureRequest(routeId.ToString());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithMatchingRouteId_ShouldSendUpdateBookCommandToHandler()
|
||||
{
|
||||
// Arrange
|
||||
Guid routeId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequest(routeId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCommand>(command =>
|
||||
command.Id == routeId &&
|
||||
command.Metadata == request.Metadata &&
|
||||
command.Format == request.Format &&
|
||||
command.Edition == request.Edition &&
|
||||
command.ASIN == request.ASIN &&
|
||||
command.ISBNs == request.ISBNs &&
|
||||
command.Contributors == request.Contributors &&
|
||||
command.Ratings == request.Ratings),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldSendCommandWithRouteId()
|
||||
{
|
||||
// Arrange
|
||||
Guid routeId = Guid.NewGuid();
|
||||
Guid bodyId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequest(routeId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCommand>(command => command.Id == routeId && command.Id != bodyId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldSendCommandWithEmptyBookId()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequest("not-a-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCommand>(command => command.Id == Guid.Empty),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsEmpty_ShouldSendCommandWithEmptyBookId()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequest(string.Empty);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCommand>(command => command.Id == Guid.Empty),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsMissing_ShouldSendCommandWithEmptyBookId()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequestWithoutId();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCommand>(command => command.Id == Guid.Empty),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
Guid routeId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId);
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_bookResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
ConfigureRequest(routeId.ToString());
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <c>id</c> route value the endpoint reads the book Id from.
|
||||
/// </summary>
|
||||
/// <param name="routeId">The raw route value of the book Id.</param>
|
||||
private void ConfigureRequest(string routeId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["id"] = routeId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Leaves the <c>id</c> route value unset.
|
||||
/// </summary>
|
||||
private void ConfigureRequestWithoutId()
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues.Remove("id");
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateBookCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookCoverEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<UpdateBookCoverCommand, Result<string>> _mockHandler;
|
||||
private readonly UpdateBookCoverEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateBookCoverEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<UpdateBookCoverCommand, Result<string>>>();
|
||||
_sut = Factory.Create<UpdateBookCoverEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
string expectedPath = "/media/books/cover.jpg";
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedPath));
|
||||
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<string> okResult = Assert.IsType<Ok<string>>(result);
|
||||
Assert.Equal(expectedPath, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRouteIdAndFile_ShouldSendUpdateBookCoverCommand()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/books/cover.jpg"));
|
||||
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCoverCommand>(command =>
|
||||
command.BookId == bookId &&
|
||||
command.Cover != null &&
|
||||
command.FileName == "cover.jpg"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldSendCommandWithEmptyBookId()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/books/cover.jpg"));
|
||||
ConfigureRequest("not-a-guid", [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCoverCommand>(command => command.BookId == Guid.Empty && command.Cover != null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormHasNoFiles_ShouldSendCommandWithNullCover()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/books/cover.jpg"));
|
||||
ConfigureRequestWithoutFiles(bookId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<Ok<string>>(result);
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCoverCommand>(command => command.BookId == bookId && command.Cover == null && command.FileName == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
|
||||
Assert.Equal("Book.NotFound", problemDetailsBody.Title);
|
||||
Assert.Equal("BookNotFound", problemDetailsBody.Detail);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
private void ConfigureRequest(Guid bookId, byte[] content, string fileName)
|
||||
{
|
||||
ConfigureRequest(bookId.ToString(), content, fileName);
|
||||
}
|
||||
|
||||
private void ConfigureRequest(string bookId, byte[] content, string fileName)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["id"] = bookId;
|
||||
MemoryStream coverStream = new(content);
|
||||
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
private void ConfigureRequestWithoutFiles(Guid bookId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["id"] = bookId.ToString();
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetBookDetailsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBookDetailsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetBookDetailsEndpoint _sut;
|
||||
private readonly GetBookRequestFixture _getBookRequestFixture = new();
|
||||
private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetBookDetailsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetBookDetailsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetBookDetailsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestBookDetailsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.Id));
|
||||
_mockApiHttpClient.GetAsync<BookDetailsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<BookDetailsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsBookDetails_ShouldReturnSuccessJsonWithBook()
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.Id));
|
||||
_mockApiHttpClient.GetAsync<BookDetailsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedBook.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="SaveBookEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveBookEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly SaveBookEndpoint _sut;
|
||||
private readonly UpdateBookRequestFixture _updateBookRequestFixture = new();
|
||||
private readonly BookDetailsDtoFixture _bookDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SaveBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public SaveBookEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<SaveBookEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithMatchingRouteId_ShouldForwardUpdateBookRequestToApi()
|
||||
{
|
||||
// Arrange
|
||||
string routeId = Guid.NewGuid().ToString();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
ConfigureRequest(routeId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", routeId)),
|
||||
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == routeId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldForwardTheRouteIdToApi()
|
||||
{
|
||||
// Arrange
|
||||
string routeId = Guid.NewGuid().ToString();
|
||||
string bodyId = Guid.NewGuid().ToString();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
request.Id = bodyId;
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
ConfigureRequest(routeId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", routeId)),
|
||||
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == routeId && forwardedRequest.Id != bodyId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldForwardGuidEmptyToApi()
|
||||
{
|
||||
// Arrange
|
||||
const string ROUTE_ID = "not-a-guid";
|
||||
string expectedId = Guid.Empty.ToString();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
ConfigureRequest(ROUTE_ID);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", expectedId)),
|
||||
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == expectedId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsMissing_ShouldForwardGuidEmptyToApi()
|
||||
{
|
||||
// Arrange
|
||||
string expectedId = Guid.Empty.ToString();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
ConfigureRequestWithoutId();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", expectedId)),
|
||||
Arg.Is<UpdateBookRequest>(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == expectedId),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUpdatedBook_ShouldReturnSuccessJsonWithBook()
|
||||
{
|
||||
// Arrange
|
||||
string routeId = Guid.NewGuid().ToString();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
ConfigureRequest(routeId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedBook.Id, jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <c>id</c> route value the endpoint reads the book Id from.
|
||||
/// </summary>
|
||||
/// <param name="routeId">The raw route value of the book Id.</param>
|
||||
private void ConfigureRequest(string routeId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["id"] = routeId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Leaves the <c>id</c> route value unset.
|
||||
/// </summary>
|
||||
private void ConfigureRequestWithoutId()
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues.Remove("id");
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateBookCoverEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookCoverEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly UpdateBookCoverEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateBookCoverEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<UpdateBookCoverEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithFile_ShouldUploadCoverToApi()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_mockApiHttpClient.PutMultipartAsync<string>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns("/media/books/cover.jpg");
|
||||
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<string>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", bookId.ToString())),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Is<string>(fileName => fileName == "cover.jpg"),
|
||||
Arg.Is<string>(fieldName => fieldName == "cover"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldUploadCoverWithEmptyBookId()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.PutMultipartAsync<string>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns("/media/books/cover.jpg");
|
||||
ConfigureRequest("not-a-guid", [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PutMultipartAsync<string>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", Guid.Empty.ToString())),
|
||||
Arg.Any<Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsCoverPath_ShouldReturnSuccessJsonWithPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string expectedPath = "/media/books/cover.jpg";
|
||||
_mockApiHttpClient.PutMultipartAsync<string>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPath);
|
||||
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedPath, jsonDocument.RootElement.GetProperty("data").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormHasNoFile_ShouldReturnBadRequestProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ConfigureRequestWithoutFiles(bookId);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.StatusCode);
|
||||
Assert.Equal("The uploaded cover image is missing.", problemDetails.ProblemDetails.Detail);
|
||||
await _mockApiHttpClient.DidNotReceive().PutMultipartAsync<string>(Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
private void ConfigureRequest(Guid bookId, byte[] content, string fileName)
|
||||
{
|
||||
ConfigureRequest(bookId.ToString(), content, fileName);
|
||||
}
|
||||
|
||||
private void ConfigureRequest(string bookId, byte[] content, string fileName)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["id"] = bookId;
|
||||
MemoryStream coverStream = new(content);
|
||||
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
private void ConfigureRequestWithoutFiles(Guid bookId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["id"] = bookId.ToString();
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user