mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 06:11:10 +00:00
Refactors the add book slice and shared media contributor model across the stack
This commit is contained in:
1 parent
3a2c80b615
commit
9a71a6d32b
61 files changed
+5223
-1384
No files matched your search
+106
@@ -0,0 +1,106 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaContributorReferenceDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorReferenceDtoMappingTests
|
||||
{
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToBookDomainEntity_WhenMappingCompleteMediaContributorReferenceDto_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
MediaContributorReferenceDto dto = _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author);
|
||||
|
||||
// Act
|
||||
Result<BookMediaContributor> result = dto.ToBookDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(dto.ContributorId, result.Value.ContributorId.Value);
|
||||
Assert.Equal(dto.Role, result.Value.Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToBookDomainEntities_WhenMappingMultipleValidMediaContributorReferenceDtos_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<MediaContributorReferenceDto> dtos =
|
||||
[
|
||||
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author),
|
||||
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Illustrator)
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<Result<BookMediaContributor>> results = dtos.ToBookDomainEntities();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(dtos.Count, results.Count());
|
||||
|
||||
List<Result<BookMediaContributor>> resultList = [.. results];
|
||||
Assert.All(resultList, result => Assert.False(result.IsFailure));
|
||||
Assert.Equal(dtos[0].ContributorId, resultList[0].Value.ContributorId.Value);
|
||||
Assert.Equal(dtos[0].Role, resultList[0].Value.Role);
|
||||
Assert.Equal(dtos[1].ContributorId, resultList[1].Value.ContributorId.Value);
|
||||
Assert.Equal(dtos[1].Role, resultList[1].Value.Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToMusicDomainEntity_WhenMappingCompleteMediaContributorReferenceDto_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
MediaContributorReferenceDto dto = _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Producer);
|
||||
|
||||
// Act
|
||||
Result<MusicMediaContributor> result = dto.ToMusicDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(dto.ContributorId, result.Value.ContributorId.Value);
|
||||
Assert.Equal(dto.Role, result.Value.Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToMusicDomainEntities_WhenMappingMultipleValidMediaContributorReferenceDtos_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<MediaContributorReferenceDto> dtos =
|
||||
[
|
||||
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Vocals),
|
||||
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Guitar)
|
||||
];
|
||||
|
||||
// Act
|
||||
IEnumerable<Result<MusicMediaContributor>> results = dtos.ToMusicDomainEntities();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(dtos.Count, results.Count());
|
||||
|
||||
List<Result<MusicMediaContributor>> resultList = [.. results];
|
||||
Assert.All(resultList, result => Assert.False(result.IsFailure));
|
||||
Assert.Equal(dtos[0].ContributorId, resultList[0].Value.ContributorId.Value);
|
||||
Assert.Equal(dtos[0].Role, resultList[0].Value.Role);
|
||||
Assert.Equal(dtos[1].ContributorId, resultList[1].Value.ContributorId.Value);
|
||||
Assert.Equal(dtos[1].Role, resultList[1].Value.Role);
|
||||
}
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
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.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
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="AddBookCommandMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddBookCommandMappingTests
|
||||
{
|
||||
private readonly AddBookCommandFixture _commandBookFixture = new();
|
||||
private readonly IsbnDtoFixture _isbnDtoFixture = new();
|
||||
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookCommand command = _commandBookFixture.Create(libraryId: libraryId.ToString());
|
||||
|
||||
// Act
|
||||
Result<Book> result = command.ToDomainEntity(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(libraryId, result.Value.LibraryId.Value);
|
||||
Assert.Equal(command.Path, result.Value.Path);
|
||||
Assert.Equal(command.Metadata!.Title, result.Value.Metadata.Title);
|
||||
Assert.Equal(command.Metadata.ReleaseInfo!.OriginalReleaseYear, result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.Value);
|
||||
Assert.Equal(command.Metadata.Genres!.Count, result.Value.Metadata.Genres.Count);
|
||||
Assert.Equal(command.Metadata.Tags!.Count, result.Value.Metadata.Tags.Count);
|
||||
Assert.Equal(command.ISBNs!.Count, result.Value.ISBNs.Count);
|
||||
Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count);
|
||||
Assert.Equal(command.Ratings!.Count, result.Value.Ratings.Count);
|
||||
Assert.True(result.Value.Format.HasValue);
|
||||
Assert.Equal(command.Format, result.Value.Format.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapRequiredPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookCommand command = _commandBookFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
isbns: [],
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
includeOptionalProperties: false);
|
||||
|
||||
// Act
|
||||
Result<Book> result = command.ToDomainEntity(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(libraryId, result.Value.LibraryId.Value);
|
||||
Assert.Equal(command.Path, result.Value.Path);
|
||||
Assert.Empty(result.Value.ISBNs);
|
||||
Assert.Empty(result.Value.Contributors);
|
||||
Assert.Empty(result.Value.Ratings);
|
||||
Assert.False(result.Value.Format.HasValue);
|
||||
Assert.False(result.Value.Edition.HasValue);
|
||||
Assert.False(result.Value.VolumeNumber.HasValue);
|
||||
Assert.False(result.Value.ASIN.HasValue);
|
||||
Assert.False(result.Value.GoodreadsId.HasValue);
|
||||
Assert.False(result.Value.LCCN.HasValue);
|
||||
Assert.False(result.Value.OCLCNumber.HasValue);
|
||||
Assert.False(result.Value.OpenLibraryId.HasValue);
|
||||
Assert.False(result.Value.LibraryThingId.HasValue);
|
||||
Assert.False(result.Value.GoogleBooksId.HasValue);
|
||||
Assert.False(result.Value.BarnesAndNobleId.HasValue);
|
||||
Assert.False(result.Value.AppleBooksId.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)]);
|
||||
|
||||
// Act
|
||||
Result<Book> result = command.ToDomainEntity(Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueMustBePositive.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenIsbnCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]);
|
||||
|
||||
// Act
|
||||
Result<Book> result = command.ToDomainEntity(Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.WrittenContent.InvalidIsbn13Format.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")]));
|
||||
|
||||
// Act
|
||||
Result<Book> result = command.ToDomainEntity(Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
+11
-12
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
@@ -21,20 +21,22 @@ public class AddBookRequestMappingTests
|
||||
{
|
||||
private readonly AddBookRequestFixture _requestFixture = new();
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
private readonly MediaContributorNameDtoFixture _mediaContributorNameDtoFixture = new();
|
||||
private readonly MediaContributorRoleDtoFixture _mediaContributorRoleDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookRequest request = _requestFixture.Create();
|
||||
|
||||
// Act
|
||||
AddBookCommand result = request.ToCommand();
|
||||
AddBookCommand result = request.ToCommand(libraryId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(libraryId.ToString(), result.LibraryId);
|
||||
Assert.Equal(request.Path, result.Path);
|
||||
Assert.Equal(request.Metadata, result.Metadata);
|
||||
Assert.Equal(request.Format, result.Format);
|
||||
Assert.Equal(request.Edition, result.Edition);
|
||||
@@ -58,15 +60,15 @@ public class AddBookRequestMappingTests
|
||||
public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookRequest request = _requestFixture.Create(
|
||||
libraryId: Guid.NewGuid(),
|
||||
path: "/books/test.epub",
|
||||
metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"),
|
||||
includeOptionalProperties: false
|
||||
);
|
||||
|
||||
// Act
|
||||
AddBookCommand result = request.ToCommand();
|
||||
AddBookCommand result = request.ToCommand(libraryId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
@@ -93,24 +95,21 @@ public class AddBookRequestMappingTests
|
||||
public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookRequest request = _requestFixture.Create(
|
||||
libraryId: Guid.NewGuid(),
|
||||
path: "/books/test.epub",
|
||||
metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"),
|
||||
isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)],
|
||||
contributors:
|
||||
[
|
||||
new(
|
||||
_mediaContributorNameDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe"),
|
||||
_mediaContributorRoleDtoFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author)
|
||||
)
|
||||
_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)
|
||||
],
|
||||
ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)],
|
||||
includeOptionalProperties: false
|
||||
);
|
||||
|
||||
// Act
|
||||
AddBookCommand result = request.ToCommand();
|
||||
AddBookCommand result = request.ToCommand(libraryId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
|
||||
-32
@@ -134,38 +134,6 @@ public class BookMetadataDtoMappingTests
|
||||
Assert.True(result.IsFailure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyMetadata_WhenLanguageIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Book book = _bookFixture.Create();
|
||||
BookMetadataDto metadata = _bookMetadataDtoFixture.Create(
|
||||
title: "A valid title",
|
||||
language: new LanguageInfoDto("", "English", "English"));
|
||||
|
||||
// Act
|
||||
Result<Success> result = book.ApplyMetadata(metadata);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyMetadata_WhenOriginalLanguageIsInvalid_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Book book = _bookFixture.Create();
|
||||
BookMetadataDto metadata = _bookMetadataDtoFixture.Create(
|
||||
title: "A valid title",
|
||||
originalLanguage: new LanguageInfoDto("", "English", "English"));
|
||||
|
||||
// Act
|
||||
Result<Success> result = book.ApplyMetadata(metadata);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyMetadata_WhenIsbnIsInvalid_ShouldReturnError()
|
||||
{
|
||||
|
||||
+149
-133
@@ -1,10 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
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;
|
||||
@@ -12,6 +14,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
|
||||
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.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.Setup;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
@@ -21,11 +24,15 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.Book
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
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;
|
||||
@@ -42,9 +49,12 @@ public class AddBookCommandHandlerTests
|
||||
private readonly IFixture _fixture;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMediaContributorRepository _mockMediaContributorRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<AddBookCommand> _mockValidator;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly Guid _userId;
|
||||
private readonly AddBookCommandHandler _sut;
|
||||
private readonly AddBookCommandFixture _commandBookFixture = new();
|
||||
@@ -53,10 +63,9 @@ public class AddBookCommandHandlerTests
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
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();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddBookCommandHandlerTests"/> class.
|
||||
@@ -69,24 +78,66 @@ public class AddBookCommandHandlerTests
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_userId = Guid.NewGuid();
|
||||
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_mediaContributorEntityFixture.Create()));
|
||||
// Default stub: saving changes succeeds.
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
// 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);
|
||||
// Default stub: the book path is inside the content locations of the library.
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
|
||||
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(true);
|
||||
// Default stub: every referenced media contributor already exists.
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
IReadOnlyCollection<Guid> contributorIds = callInfo.Arg<IReadOnlyCollection<Guid>>();
|
||||
return Result.From<IReadOnlyList<MediaContributorEntity>>([.. contributorIds.Select(contributorId => new MediaContributorEntity
|
||||
{
|
||||
Id = contributorId,
|
||||
DisplayName = contributorId.ToString(),
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
})]);
|
||||
});
|
||||
|
||||
IValidator<AddBookCommand> mockValidator = Substitute.For<IValidator<AddBookCommand>>();
|
||||
mockValidator.Validate(Arg.Any<AddBookCommand>())
|
||||
.Returns([]);
|
||||
_sut = new AddBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, mockValidator);
|
||||
_mockValidator = mockValidator;
|
||||
_sut = new AddBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<AddBookCommand>())
|
||||
.Returns([Errors.WrittenContent.IsbnListCannotBeNull]);
|
||||
|
||||
// Act
|
||||
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.IsbnListCannotBeNull, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -95,8 +146,15 @@ public class AddBookCommandHandlerTests
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create();
|
||||
|
||||
BookEntity? insertedEntity = null;
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
insertedEntity = callInfo.Arg<BookEntity>();
|
||||
return Result.Created;
|
||||
});
|
||||
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<BookEntity?>(insertedEntity));
|
||||
|
||||
// Act
|
||||
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
|
||||
@@ -127,6 +185,26 @@ public class AddBookCommandHandlerTests
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveChangesDetectsAConcurrentDuplicatePath_ShouldReturnThePersistenceError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create();
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalledWithInvalidISBN_ShouldReturnFailureResult()
|
||||
{
|
||||
@@ -216,53 +294,17 @@ public class AddBookCommandHandlerTests
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLanguageInfoCreationFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: "", languageName: "English")));
|
||||
|
||||
// Act
|
||||
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
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_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: "", languageName: "English")));
|
||||
|
||||
// Act
|
||||
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
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
|
||||
Guid firstContributorId = Guid.NewGuid();
|
||||
Guid secondContributorId = Guid.NewGuid();
|
||||
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)
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Author),
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.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 =>
|
||||
@@ -270,37 +312,33 @@ public class AddBookCommandHandlerTests
|
||||
insertedEntity = callInfo.Arg<BookEntity>();
|
||||
return Result.Created;
|
||||
});
|
||||
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<BookEntity?>(insertedEntity));
|
||||
|
||||
// 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);
|
||||
Assert.Contains(insertedEntity.BookContributors, contributor => contributor.MediaContributorId == firstContributorId && contributor.Role == MediaContributorRole.Author);
|
||||
Assert.Contains(insertedEntity.BookContributors, contributor => contributor.MediaContributorId == secondContributorId && contributor.Role == MediaContributorRole.Illustrator);
|
||||
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()
|
||||
public async Task HandleAsync_WhenContributorsHaveTheSameIdAndRole_ShouldLinkThemOnlyOnce()
|
||||
{
|
||||
// Arrange
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
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)
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author),
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author),
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.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 =>
|
||||
@@ -308,73 +346,22 @@ public class AddBookCommandHandlerTests
|
||||
insertedEntity = callInfo.Arg<BookEntity>();
|
||||
return Result.Created;
|
||||
});
|
||||
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<BookEntity?>(insertedEntity));
|
||||
|
||||
// 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");
|
||||
Assert.All(insertedEntity.BookContributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
|
||||
Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
|
||||
Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.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()
|
||||
{
|
||||
@@ -407,33 +394,62 @@ public class AddBookCommandHandlerTests
|
||||
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>());
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == Guid.Parse(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()
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// 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;
|
||||
});
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create();
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(null));
|
||||
|
||||
// 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>());
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookPathIsNotWithinTheLibraryContentLocations_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create();
|
||||
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookPathMustBeWithinLibraryContentLocations, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([]));
|
||||
|
||||
// Act
|
||||
Result<BookResponse> result = await _sut.HandleAsync(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+60
-86
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
@@ -35,7 +35,20 @@ public class AddBookCommandValidatorTests
|
||||
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
|
||||
private readonly IsbnDtoFixture _isbnDtoFixture = new();
|
||||
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
|
||||
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenPathIsLongerThan2048Characters_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".epub");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.BookPathMustBeMaximum2048CharactersLong);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTitleIsNull_ShouldHaveValidationError()
|
||||
@@ -479,6 +492,19 @@ public class AddBookCommandValidatorTests
|
||||
result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1))));
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
@@ -557,6 +583,19 @@ public class AddBookCommandValidatorTests
|
||||
result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenOriginalLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1))));
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError()
|
||||
{
|
||||
@@ -1224,7 +1263,7 @@ public class AddBookCommandValidatorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldAddBook()
|
||||
public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false);
|
||||
@@ -1250,7 +1289,7 @@ public class AddBookCommandValidatorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnBadRequest()
|
||||
public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(51));
|
||||
@@ -1367,7 +1406,7 @@ public class AddBookCommandValidatorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddBook_WhenCalledWithEmptyAppleBooksId_ShouldAddBook()
|
||||
public void Validate_WhenCalledWithEmptyAppleBooksId_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false);
|
||||
@@ -1380,7 +1419,7 @@ public class AddBookCommandValidatorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddBook_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError()
|
||||
public void Validate_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "id123456");
|
||||
@@ -1393,7 +1432,7 @@ public class AddBookCommandValidatorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddBook_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError()
|
||||
public void Validate_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "invalid_id");
|
||||
@@ -1497,120 +1536,55 @@ public class AddBookCommandValidatorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithNullContributors_ShouldHaveValidationError()
|
||||
public void Validate_WhenContributorsIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false);
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create() with { Contributors = null };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithNullContributorName_ShouldHaveValidationError()
|
||||
public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(null, new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author))]);
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorNameCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithInvalidLengthContributorDisplayName_ShouldHaveValidationError()
|
||||
public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(101))]);
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong);
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithEmptyContributorDisplayName_ShouldHaveValidationError()
|
||||
public void Validate_WhenContributorRoleIsInvalid_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]);
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithInvalidLengthContributorLegalName_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), new Faker().Random.String2(101)), new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author))]);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithNullContributorRole_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), null)]);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorRoleCannotBeNull);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithEmptyContributorRoleName_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto(null, MediaContributorRoleCategory.Author))]);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.RoleNameCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithInvalidLengthContributorRoleName_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto(new Faker().Random.String2(51), MediaContributorRoleCategory.Author))]);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithEmptyContributorRoleCategory_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto("author", null))]);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryCannotBeEmpty);
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -1708,12 +1682,12 @@ public class AddBookCommandValidatorTests
|
||||
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty);
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty.ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.BookLibraryCannotBeNull);
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -24,7 +24,7 @@ public class MediaContributorDtoTests
|
||||
// Arrange
|
||||
MediaContributorDto expected = new(
|
||||
new MediaContributorNameDto("John Smith", "Johnathan Smith"),
|
||||
new MediaContributorRoleDto("Author", MediaContributorRoleCategory.Author)
|
||||
MediaContributorRole.Author
|
||||
);
|
||||
|
||||
// Act
|
||||
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.DTO.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaContributorRoleDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorRoleDtoTests
|
||||
{
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_WhenSerializingRole_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorRoleDto expected = new("Author", MediaContributorRoleCategory.Author);
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
MediaContributorRoleDto? actual = JsonSerializer.Deserialize<MediaContributorRoleDto>(json, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(actual);
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorRoleDto first = new("Illustrator", null);
|
||||
MediaContributorRoleDto second = new("Illustrator", null);
|
||||
|
||||
// Act
|
||||
bool areEqual = first == second;
|
||||
|
||||
// Assert
|
||||
Assert.True(areEqual);
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
@@ -36,7 +36,6 @@ public class AddBookRequestTests
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut);
|
||||
Assert.NotEqual(Guid.Empty, sut.LibraryId);
|
||||
Assert.False(string.IsNullOrWhiteSpace(sut.Path));
|
||||
Assert.NotNull(sut.Metadata);
|
||||
Assert.NotNull(sut.ISBNs);
|
||||
@@ -83,10 +82,9 @@ public class AddBookRequestTests
|
||||
AddBookRequest sut = _addBookRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
(Guid libraryId, string path, 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;
|
||||
(string path, 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<MediaContributorReferenceDto>? contributors, List<BookRatingDto>? ratings) = sut;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(sut.LibraryId, libraryId);
|
||||
Assert.Equal(sut.Path, path);
|
||||
Assert.Equal(sut.Metadata, metadata);
|
||||
Assert.Equal(sut.Format, format);
|
||||
|
||||
+104
-48
@@ -96,6 +96,50 @@ public class BookRepositoryTests
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<BookEntity>()); // Only the existing book should be in the context.
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherBookOfTheSameLibraryHasTheSamePath_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity existingBook = _bookEntityFixture.Create();
|
||||
existingBook.LibraryId = libraryId;
|
||||
existingBook.Path = "/books/existing.epub";
|
||||
_mockContext.Books.Add(existingBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
BookEntity bookModel = _bookEntityFixture.Create();
|
||||
bookModel.LibraryId = libraryId;
|
||||
bookModel.Path = "/books/existing.epub";
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherLibraryHasABookWithTheSamePath_ShouldAddBookToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity existingBook = _bookEntityFixture.Create();
|
||||
existingBook.Path = "/books/existing.epub";
|
||||
_mockContext.Books.Add(existingBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
BookEntity bookModel = _bookEntityFixture.Create();
|
||||
bookModel.LibraryId = Guid.NewGuid();
|
||||
bookModel.Path = "/books/existing.epub";
|
||||
|
||||
// Act
|
||||
Result<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes()
|
||||
{
|
||||
@@ -151,54 +195,66 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooks()
|
||||
public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooksOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
List<BookEntity> books = _bookEntityFixture.CreateMany(3);
|
||||
foreach (BookEntity book in books)
|
||||
book.LibraryId = libraryId;
|
||||
_mockContext.Books.AddRange(books);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<BookEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync<LibraryFilterDto>(filterModel: filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Equal(3, result.Value.Count());
|
||||
Assert.Equal(books, result.Value);
|
||||
Assert.Equal(3, result.Value.Data.Count);
|
||||
Assert.Equal([.. books.OrderBy(book => book.Id)], [.. result.Value.Data.OrderBy(book => book.Id)]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenNoBooksExist_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<BookEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync<LibraryFilterDto>(filterModel: filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Empty(result.Value);
|
||||
Assert.Empty(result.Value.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_WhenCalled_ShouldIncludeRelatedEntities()
|
||||
public async Task GetAllAsync_WhenPaginationIsNotProvided_ShouldIncludeRelatedEntities()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
|
||||
book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
|
||||
book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)];
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<IEnumerable<BookEntity>> result = await _sut.GetAllAsync(CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync<LibraryFilterDto>(filterModel: filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value);
|
||||
Assert.Single(result.Value);
|
||||
BookEntity retrievedBook = result.Value.First();
|
||||
Assert.Single(result.Value.Data);
|
||||
BookEntity retrievedBook = result.Value.Data.First();
|
||||
Assert.Equal(2, retrievedBook.Tags.Count);
|
||||
Assert.Equal(2, retrievedBook.Genres.Count);
|
||||
Assert.Equal(2, retrievedBook.ISBNs.Count);
|
||||
@@ -441,14 +497,14 @@ public class BookRepositoryTests
|
||||
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)];
|
||||
storedBook.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, role: MediaContributorRole.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)];
|
||||
data.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Illustrator)];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
@@ -467,11 +523,11 @@ public class BookRepositoryTests
|
||||
BookContributorEntity retrievedContributor = Assert.Single(retrievedBook.BookContributors);
|
||||
Assert.Equal("9780261102693", retrievedIsbn.Value);
|
||||
Assert.Equal(3.5M, retrievedRating.Value);
|
||||
Assert.Equal(MediaContributorRoleCategory.Illustrator, retrievedContributor.RoleCategory);
|
||||
Assert.Equal(MediaContributorRole.Illustrator, retrievedContributor.Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedBooks()
|
||||
public async Task GetAllAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedBooks()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -485,7 +541,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -497,14 +553,14 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError()
|
||||
public async Task GetAllAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
BaseFilterDto filter = _baseFilterDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
@@ -512,14 +568,14 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError()
|
||||
public async Task GetAllAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
@@ -527,7 +583,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenPaginationDataIsNull_ShouldReturnAllBooks()
|
||||
public async Task GetAllAsync_WhenPaginationDataIsNull_ShouldReturnAllBooks()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -540,7 +596,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(null, null, null, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -552,7 +608,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingBooks()
|
||||
public async Task GetAllAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingBooks()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -569,7 +625,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Fellowship");
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -579,7 +635,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenPageSizeSmallerThanBookCount_ShouldReturnCorrectPageMetadata()
|
||||
public async Task GetAllAsync_WhenPageSizeSmallerThanBookCount_ShouldReturnCorrectPageMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -593,7 +649,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -605,7 +661,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenSortByTitleDescending_ShouldReturnBooksInDescendingOrder()
|
||||
public async Task GetAllAsync_WhenSortByTitleDescending_ShouldReturnBooksInDescendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -622,7 +678,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "title", SortOrder.Descending, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "title", SortOrder.Descending, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -630,7 +686,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenCalled_ShouldIncludeRelatedEntities()
|
||||
public async Task GetAllAsync_WhenPaginationIsProvided_ShouldIncludeRelatedEntities()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -647,7 +703,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -733,8 +789,8 @@ public class BookRepositoryTests
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
_mockContext.BookContributors.AddRange(
|
||||
_bookContributorEntityFixture.Create(bookId: firstBook.Id, mediaContributorId: author.Id, roleName: "Author", roleCategory: MediaContributorRoleCategory.Author),
|
||||
_bookContributorEntityFixture.Create(bookId: secondBook.Id, mediaContributorId: translator.Id, roleName: "Translator", roleCategory: MediaContributorRoleCategory.Translator));
|
||||
_bookContributorEntityFixture.Create(bookId: firstBook.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author),
|
||||
_bookContributorEntityFixture.Create(bookId: secondBook.Id, mediaContributorId: translator.Id, role: MediaContributorRole.Translator));
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
@@ -786,7 +842,7 @@ public class BookRepositoryTests
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<BookEntity?> result = await _sut.GetByIdAsync(book.Id, CancellationToken.None);
|
||||
Result<BookEntity?> result = await _sut.GetByIdAsync(book.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -797,7 +853,7 @@ public class BookRepositoryTests
|
||||
public async Task GetByIdAsync_WhenBookDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<BookEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
Result<BookEntity?> result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -817,7 +873,7 @@ public class BookRepositoryTests
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<BookEntity?> result = await _sut.GetByIdAsync(book.Id, CancellationToken.None);
|
||||
Result<BookEntity?> result = await _sut.GetByIdAsync(book.Id, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -857,7 +913,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenSortByLanguageCodeAscending_ShouldReturnBooksInAscendingOrder()
|
||||
public async Task GetAllAsync_WhenSortByLanguageCodeAscending_ShouldReturnBooksInAscendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -874,7 +930,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "languageCode", SortOrder.Ascending, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "languageCode", SortOrder.Ascending, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -882,7 +938,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenSortByLanguageCodeDescending_ShouldReturnBooksInDescendingOrder()
|
||||
public async Task GetAllAsync_WhenSortByLanguageCodeDescending_ShouldReturnBooksInDescendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -899,7 +955,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "languageCode", SortOrder.Descending, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "languageCode", SortOrder.Descending, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -907,7 +963,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenSortByFormatAscending_ShouldReturnBooksInAscendingOrder()
|
||||
public async Task GetAllAsync_WhenSortByFormatAscending_ShouldReturnBooksInAscendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -924,7 +980,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "format", SortOrder.Ascending, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "format", SortOrder.Ascending, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -932,7 +988,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenSortByFormatDescending_ShouldReturnBooksInDescendingOrder()
|
||||
public async Task GetAllAsync_WhenSortByFormatDescending_ShouldReturnBooksInDescendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -949,7 +1005,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "format", SortOrder.Descending, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "format", SortOrder.Descending, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -957,7 +1013,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenSortByMetadataProviderAscending_ShouldReturnBooksInAscendingOrder()
|
||||
public async Task GetAllAsync_WhenSortByMetadataProviderAscending_ShouldReturnBooksInAscendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -974,7 +1030,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "metadataProvider", SortOrder.Ascending, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "metadataProvider", SortOrder.Ascending, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -982,7 +1038,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenSortByMetadataProviderDescending_ShouldReturnBooksInDescendingOrder()
|
||||
public async Task GetAllAsync_WhenSortByMetadataProviderDescending_ShouldReturnBooksInDescendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -999,7 +1055,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "metadataProvider", SortOrder.Descending, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, "metadataProvider", SortOrder.Descending, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -1007,7 +1063,7 @@ public class BookRepositoryTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPaginatedAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix()
|
||||
public async Task GetAllAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -1022,7 +1078,7 @@ public class BookRepositoryTests
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: true);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
|
||||
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaContributorRole"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorRoleTests
|
||||
{
|
||||
private readonly MediaContributorRoleFixture _mediaContributorRoleFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithDisplayNameAndCategory_ShouldCreateRole()
|
||||
{
|
||||
// Act
|
||||
Result<MediaContributorRole> result = MediaContributorRole.Create("Author", MediaContributorRoleCategory.Author);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Author", result.Value.DisplayName);
|
||||
Assert.Equal(MediaContributorRoleCategory.Author, result.Value.Category);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithEmptyDisplayName_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<MediaContributorRole> result = MediaContributorRole.Create(" ", MediaContributorRoleCategory.Author);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.MediaContributors.MediaContributorRoleNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
|
||||
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
|
||||
|
||||
// Act
|
||||
bool result = firstRole.Equals(secondRole);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentDisplayName_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
|
||||
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Writer", category: MediaContributorRoleCategory.Author);
|
||||
|
||||
// Act
|
||||
bool result = firstRole.Equals(secondRole);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentCategory_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
|
||||
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Translator);
|
||||
|
||||
// Act
|
||||
bool result = firstRole.Equals(secondRole);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+87
-1
@@ -43,11 +43,13 @@ public class AddBookEndpointTests
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithBookResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookRequest request = _addBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookResponse expectedResponse = _bookResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
ConfigureRequest(libraryId.ToString());
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -87,10 +89,12 @@ public class AddBookEndpointTests
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToHandler()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookRequest request = _addBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequest(libraryId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -98,7 +102,7 @@ public class AddBookEndpointTests
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<AddBookCommand>(command =>
|
||||
command.LibraryId == request.LibraryId &&
|
||||
command.LibraryId == libraryId.ToString() &&
|
||||
command.Path == request.Path),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
@@ -130,4 +134,86 @@ public class AddBookEndpointTests
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookRequest request = _addBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Error.Validation(description: "LibraryIdCannotBeEmpty");
|
||||
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
ConfigureRequest(libraryId.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[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendCommandWithRawRouteValue()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest request = _addBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequest("not-a-library-guid");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<AddBookCommand>(command => command.LibraryId == "not-a-library-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest request = _addBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequestWithoutLibraryId();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<AddBookCommand>(command => command.LibraryId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <c>libraryId</c> route value the endpoint reads the identifier from.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The raw route value of the library Id.</param>
|
||||
private void ConfigureRequest(string libraryId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Leaves the <c>libraryId</c> route value unset.
|
||||
/// </summary>
|
||||
private void ConfigureRequestWithoutLibraryId()
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user