mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 13:01:10 +00:00
Adds AddBook unit tests
This commit is contained in:
1 parent
bd2880457c
commit
a3e956a165
12 files changed
+2579
-13
No files matched your search
+1
-2
@@ -60,7 +60,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
|
||||
if (request.Series != null)
|
||||
{
|
||||
// TODO: add logic to search the book series repository for existing book series, based on the provided title
|
||||
// TODO: uncomment integration tests about series
|
||||
// TODO: uncomment integration and unit tests about series
|
||||
}
|
||||
var domainRatingsResult = request.Ratings.ConvertAll(rating => BookRating.Create(
|
||||
rating.Value ?? default,
|
||||
@@ -86,7 +86,6 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
|
||||
return errors;
|
||||
List<Tag> domainTags = domainTagsResult.Select(tag => tag.Value).ToList();
|
||||
|
||||
|
||||
var domainIsbnsResult = request.ISBNs.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!));
|
||||
errors = domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors).ToList();
|
||||
if (errors.Count != 0)
|
||||
|
||||
+9
@@ -3,6 +3,7 @@ using ErrorOr;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
using System.Diagnostics;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects;
|
||||
@@ -86,6 +87,14 @@ public class WrittenContentMetadata : BaseMetadata
|
||||
Optional<string> publisher,
|
||||
Optional<int> pageCount)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(title))
|
||||
return Errors.Metadata.TitleCannotBeEmpty;
|
||||
if (releaseInfo is null)
|
||||
return Errors.Metadata.ReleaseInfoCannotBeNull;
|
||||
if (genres is null)
|
||||
return Errors.Metadata.GenresListCannotBeNull;
|
||||
if (tags is null)
|
||||
return Errors.Metadata.TagsListCannotBeNull;
|
||||
return new WrittenContentMetadata(
|
||||
title,
|
||||
originalTitle,
|
||||
|
||||
+2
-2
@@ -26,7 +26,7 @@ public class BooksControllerTests : IClassFixture<LuminaApiFactory>
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly RequestBookFixture _requestBookFixture;
|
||||
private readonly AddBookRequestFixture _requestBookFixture;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new();
|
||||
#endregion
|
||||
|
||||
@@ -39,7 +39,7 @@ public class BooksControllerTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = _apiFactory.CreateClient();
|
||||
_requestBookFixture = new RequestBookFixture();
|
||||
_requestBookFixture = new AddBookRequestFixture();
|
||||
_jsonOptions.Converters.Add(new BookJsonConverter());
|
||||
}
|
||||
#endregion
|
||||
|
||||
+4
-8
@@ -13,10 +13,10 @@ using System.Diagnostics.CodeAnalysis;
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksControllerTests"/> class.
|
||||
/// Fixture class for the <see cref="AddBookRequest"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RequestBookFixture
|
||||
public class AddBookRequestFixture
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly Fixture _fixture;
|
||||
@@ -26,9 +26,9 @@ public class RequestBookFixture
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RequestBookFixture"/> class.
|
||||
/// Initializes a new instance of the <see cref="AddBookRequestFixture"/> class.
|
||||
/// </summary>
|
||||
public RequestBookFixture()
|
||||
public AddBookRequestFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
|
||||
@@ -271,10 +271,6 @@ public class RequestBookFixture
|
||||
var releaseYear = _random.Next(2000, 2010);
|
||||
var reReleaseYear = _random.Next(2010, 2020);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
_fixture.Register(() => new ReleaseInfoDto(
|
||||
_faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)),
|
||||
releaseYear,
|
||||
+1
-1
@@ -14,7 +14,7 @@ using System.Diagnostics.CodeAnalysis;
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Controllers.Books.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksControllerTests"/> class.
|
||||
/// Fixture class for the <see cref="Book"/> domain entity.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DomainBookFixture
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Contains extension methods for the <see cref="Faker"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class BogusExtensions
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Adds <see cref="DateOnly"/> random data generation support to the <see cref="Faker"/> class.
|
||||
/// </summary>
|
||||
/// <param name="faker">The faker instance to extend.</param>
|
||||
/// <returns>A random<see cref="DateOnly"/> instance.</returns>
|
||||
public static DateOnly DateOnly(this Faker faker)
|
||||
{
|
||||
return System.DateOnly.FromDateTime(faker.Date.Past());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds <see cref="DateOnly"/> random data generation within a specified interval support to the <see cref="Faker"/> class.
|
||||
/// </summary>
|
||||
/// <param name="faker">The faker instance to extend.</param>
|
||||
/// <param name="start">The start of the interval.</param>
|
||||
/// <param name="end">The end of the interval.</param>
|
||||
/// <returns>A random<see cref="DateOnly"/> instance.</returns>
|
||||
public static DateOnly DateOnlyBetween(this Faker faker, DateOnly start, DateOnly end)
|
||||
{
|
||||
var startDateTime = start.ToDateTime(TimeOnly.MinValue);
|
||||
var endDateTime = end.ToDateTime(TimeOnly.MinValue);
|
||||
return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture.Kernel;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a specimen builder for the <see cref="DateOnly"/> type.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DateOnlySpecimenBuilder : ISpecimenBuilder
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Adds <see cref="DateOnly"/> support to the AutoFixture library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to process.</param>
|
||||
/// <param name="context">The context within which the specimen is created.</param>
|
||||
/// <returns>A specimen based on the request.</returns>
|
||||
public object Create(object request, ISpecimenContext context)
|
||||
{
|
||||
if (request is Type type && type == typeof(DateOnly))
|
||||
return DateOnly.FromDateTime(DateTime.Now);
|
||||
return new NoSpecimen();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture.Kernel;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a specimen builder for the <see cref="DateOnly"/> type.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class NullableDateOnlySpecimenBuilder : ISpecimenBuilder
|
||||
{
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Adds <see cref="DateOnly?"/> support to the AutoFixture library.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to process.</param>
|
||||
/// <param name="context">The context within which the specimen is created.</param>
|
||||
/// <returns>A specimen based on the request.</returns>
|
||||
public object Create(object request, ISpecimenContext context)
|
||||
{
|
||||
if (request is Type type && type == typeof(DateOnly?))
|
||||
return (DateOnly?)DateOnly.FromDateTime(DateTime.Now);
|
||||
return new NoSpecimen();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using ErrorOr;
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Models.Books;
|
||||
using Lumina.Application.Common.Models.Common;
|
||||
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.Fixtures;
|
||||
using Lumina.Domain.Common.Enums;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
|
||||
using MapsterMapper;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AddBookCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddBookCommandHandlerTests
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly IFixture _fixture;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IMapper _mockMapper;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly AddBookCommandHandler _sut;
|
||||
private readonly AddBookCommandFixture _commandBookFixture;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddBookCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public AddBookCommandHandlerTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
|
||||
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockMapper = Substitute.For<IMapper>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
|
||||
_mockUnitOfWork.GetRepository<IBookRepository>().Returns(_mockBookRepository);
|
||||
|
||||
_sut = new AddBookCommandHandler(_mockUnitOfWork, _mockMapper);
|
||||
_commandBookFixture = new AddBookCommandFixture();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
[Fact]
|
||||
public async Task Handle_WhenCalledWithValidCommand_ShouldReturnSuccessResult()
|
||||
{
|
||||
// Arrange
|
||||
var bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
var bookDto = _fixture.Create<BookDto>();
|
||||
|
||||
_mockMapper.Map<BookDto>(Arg.Any<Book>()).Returns(bookDto);
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
var result = await _sut.Handle(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeFalse();
|
||||
result.Value.Should().BeOfType<Book>();
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenBookCreationFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
var bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
bookCommand = bookCommand with { Metadata = bookCommand.Metadata with { Title = null } };
|
||||
|
||||
// Act
|
||||
var result = await _sut.Handle(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.Errors.Should().Contain(e => e.Code == Errors.Metadata.TitleCannotBeEmpty.Code);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenRepositoryInsertFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
var bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
var bookDto = _fixture.Create<BookDto>();
|
||||
|
||||
_mockMapper.Map<BookDto>(Arg.Any<Book>()).Returns(bookDto);
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.WrittenContent.BookAlreadyExists);
|
||||
|
||||
// Act
|
||||
var result = await _sut.Handle(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.Errors.Should().Contain(Errors.WrittenContent.BookAlreadyExists);
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenCalledWithInvalidISBN_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
var bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
bookCommand = bookCommand with { ISBNs = [new IsbnDto("invalid", IsbnFormat.Isbn13)] };
|
||||
|
||||
// Act
|
||||
var result = await _sut.Handle(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.Errors.Should().Contain(e => e.Code == Errors.WrittenContent.InvalidIsbn13Format.Code);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenCalledWithInvalidRating_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
var bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
bookCommand = bookCommand with { Ratings = [new BookRatingDto(-1, 5, null, null)] };
|
||||
|
||||
// Act
|
||||
var result = await _sut.Handle(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.Errors.Should().Contain(e => e.Code == Errors.Metadata.RatingValueMustBePositive.Code);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenGenreCreationFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
var bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
bookCommand = bookCommand with
|
||||
{
|
||||
Metadata = bookCommand.Metadata with
|
||||
{
|
||||
Genres = [new GenreDto("")]
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
var result = await _sut.Handle(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.Errors.Should().Contain(e => e.Code == Errors.Metadata.GenreNameCannotBeEmpty.Code);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenTagCreationFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
var bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
bookCommand = bookCommand with
|
||||
{
|
||||
Metadata = bookCommand.Metadata with
|
||||
{
|
||||
Tags = [new TagDto("")]
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
var result = await _sut.Handle(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.Errors.Should().Contain(e => e.Code == Errors.Metadata.TagNameCannotBeEmpty.Code);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenReleaseInfoCreationFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
var bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
bookCommand = bookCommand with
|
||||
{
|
||||
Metadata = bookCommand.Metadata with
|
||||
{
|
||||
ReleaseInfo = new ReleaseInfoDto(
|
||||
OriginalReleaseDate: new DateOnly(2025, 1, 1),
|
||||
ReReleaseDate: new DateOnly(2024, 1, 1),
|
||||
OriginalReleaseYear: null,
|
||||
ReReleaseYear: null,
|
||||
ReleaseCountry: null,
|
||||
ReleaseVersion: null
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
var result = await _sut.Handle(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.Errors.Should().Contain(e => e.Code == Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Code);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenLanguageInfoCreationFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
var bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
bookCommand = bookCommand with
|
||||
{
|
||||
Metadata = bookCommand.Metadata with
|
||||
{
|
||||
Language = new LanguageInfoDto("", "English", null)
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
var result = await _sut.Handle(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.Errors.Should().Contain(e => e.Code == Errors.Metadata.LanguageCodeCannotBeEmpty.Code);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
var bookCommand = _commandBookFixture.CreateCommandBook();
|
||||
bookCommand = bookCommand with
|
||||
{
|
||||
Metadata = bookCommand.Metadata with
|
||||
{
|
||||
OriginalLanguage = new LanguageInfoDto("", "English", null)
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
var result = await _sut.Handle(bookCommand, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsError.Should().BeTrue();
|
||||
result.Errors.Should().Contain(e => e.Code == Errors.Metadata.LanguageCodeCannotBeEmpty.Code);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
+1858
File diff suppressed because it is too large.
Load diff
+333
@@ -0,0 +1,333 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.Models.Books;
|
||||
using Lumina.Application.Common.Models.Common;
|
||||
using Lumina.Application.Common.Models.Contributors;
|
||||
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Enums;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AddBookCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddBookCommandFixture
|
||||
{
|
||||
#region ================================================================== FIELD MEMBERS ================================================================================
|
||||
private readonly Fixture _fixture;
|
||||
private readonly Random _random = new();
|
||||
private readonly Faker _faker;
|
||||
#endregion
|
||||
|
||||
#region ====================================================================== CTOR =====================================================================================
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddBookCommandFixture"/> class.
|
||||
/// </summary>
|
||||
public AddBookCommandFixture()
|
||||
{
|
||||
_fixture = new Fixture();
|
||||
_fixture.Customizations.Add(new DateOnlySpecimenBuilder());
|
||||
_fixture.Customizations.Add(new NullableDateOnlySpecimenBuilder());
|
||||
_faker = new Faker();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ===================================================================== METHODS ===================================================================================
|
||||
/// <summary>
|
||||
/// Creates a random valid command to add a book.
|
||||
/// </summary>
|
||||
/// <returns>The created command to add a book.</returns>
|
||||
public AddBookCommand CreateCommandBook()
|
||||
{
|
||||
var releaseYear = _random.Next(2000, 2010);
|
||||
var reReleaseYear = _random.Next(2010, 2020);
|
||||
|
||||
var releaseInfo = new Faker<ReleaseInfoDto>()
|
||||
.CustomInstantiator(f => new ReleaseInfoDto(
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default
|
||||
))
|
||||
.RuleFor(x => x.OriginalReleaseDate, _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)))
|
||||
.RuleFor(x => x.OriginalReleaseYear, releaseYear)
|
||||
.RuleFor(x => x.ReReleaseDate, _faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)))
|
||||
.RuleFor(x => x.ReReleaseYear, reReleaseYear)
|
||||
.RuleFor(x => x.ReleaseCountry, f => f.Random.String2(2))
|
||||
.RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.Generate();
|
||||
|
||||
var genre = new Faker<GenreDto>()
|
||||
.CustomInstantiator(f => new GenreDto(
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
var tag = new Faker<TagDto>()
|
||||
.CustomInstantiator(f => new TagDto(
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
var mediaContributorRole = new Faker<MediaContributorRoleDto>()
|
||||
.CustomInstantiator(f => new MediaContributorRoleDto(
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
var mediaContributor = new Faker<MediaContributorDto>()
|
||||
.CustomInstantiator(f => new MediaContributorDto(
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(e => e.Role, mediaContributorRole);
|
||||
|
||||
var rating = new Faker<BookRatingDto>()
|
||||
.CustomInstantiator(f => new BookRatingDto(
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default
|
||||
))
|
||||
.RuleFor(e => e.Value, _random.Next(1, 5))
|
||||
.RuleFor(e => e.MaxValue, 5)
|
||||
.RuleFor(e => e.Source, _fixture.Create<BookRatingSource>())
|
||||
.RuleFor(e => e.VoteCount, _random.Next(1, 1000));
|
||||
|
||||
var language = new Faker<LanguageInfoDto>()
|
||||
.CustomInstantiator(f => new LanguageInfoDto(
|
||||
default!,
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
|
||||
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
var originalLanguage = new Faker<LanguageInfoDto>()
|
||||
.CustomInstantiator(f => new LanguageInfoDto(
|
||||
default!,
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(e => e.LanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(e => e.LanguageCode, f => f.Random.String2(2))
|
||||
.RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50)));
|
||||
|
||||
var metadata = new Faker<WrittenContentMetadataDto>()
|
||||
.CustomInstantiator(f => new WrittenContentMetadataDto(
|
||||
default!,
|
||||
default,
|
||||
default,
|
||||
default!,
|
||||
default!,
|
||||
default!,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default
|
||||
))
|
||||
.RuleFor(x => x.Title, f => f.Random.String2(f.Random.Number(1, 255)))
|
||||
.RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255)))
|
||||
.RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000)))
|
||||
.RuleFor(x => x.ReleaseInfo, releaseInfo)
|
||||
.RuleFor(p => p.Genres, f => genre.Generate(f.Random.Number(1, 5)))
|
||||
.RuleFor(x => x.Tags, f => tag.Generate(f.Random.Number(1, 5)))
|
||||
.RuleFor(x => x.Language, language)
|
||||
.RuleFor(x => x.OriginalLanguage, originalLanguage)
|
||||
.RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100)))
|
||||
.RuleFor(x => x.PageCount, _random.Next(100, 300));
|
||||
|
||||
var isbn = new Faker<IsbnDto>()
|
||||
.CustomInstantiator(f => new IsbnDto(
|
||||
default!,
|
||||
default
|
||||
))
|
||||
.RuleFor(i => i.Value, f =>
|
||||
{
|
||||
var isIsbn13 = f.Random.Bool();
|
||||
if (isIsbn13)
|
||||
{
|
||||
var prefix = f.Random.Bool() ? "978" : "979";
|
||||
var group = f.Random.Number(0, 99999).ToString().PadLeft(5, '0');
|
||||
var publisher = f.Random.Number(0, 999999).ToString().PadLeft(6, '0');
|
||||
var title = f.Random.Number(0, 99).ToString().PadLeft(2, '0');
|
||||
string isbn = $"{prefix}{group.Substring(0, 1)}{publisher}{title}";
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 12; i++)
|
||||
sum += (i % 2 == 0 ? 1 : 3) * int.Parse(isbn[i].ToString());
|
||||
int checkDigit = (10 - (sum % 10)) % 10;
|
||||
return $"{prefix}-{group.Substring(0, 1)}-{publisher}-{title}-{checkDigit}";
|
||||
}
|
||||
else
|
||||
{
|
||||
var digits = new int[9];
|
||||
for (int i = 0; i < 9; i++)
|
||||
digits[i] = f.Random.Number(0, 9);
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 9; i++)
|
||||
sum += (10 - i) * digits[i];
|
||||
int checkDigit = (11 - (sum % 11)) % 11;
|
||||
string checkChar = checkDigit == 10 ? "X" : checkDigit.ToString();
|
||||
return $"{digits[0]}-{digits[1]}{digits[2]}-{digits[3]}{digits[4]}{digits[5]}{digits[6]}{digits[7]}{digits[8]}-{checkChar}";
|
||||
}
|
||||
})
|
||||
.RuleFor(i => i.Format, (f, i) => i.Value!.Length > 13 ? IsbnFormat.Isbn13 : IsbnFormat.Isbn10);
|
||||
|
||||
return new Faker<AddBookCommand>()
|
||||
.CustomInstantiator(f => new AddBookCommand(
|
||||
default!,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default,
|
||||
default!,
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.Metadata, metadata)
|
||||
.RuleFor(x => x.Format, _fixture.Create<BookFormat>())
|
||||
.RuleFor(x => x.Edition, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.VolumeNumber, _random.Next(1, 3))
|
||||
.RuleFor(x => x.ASIN, f => f.Random.String2(10))
|
||||
.RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString())
|
||||
.RuleFor(x => x.LCCN, f =>
|
||||
{
|
||||
var letters = new string(Enumerable.Range(0, f.Random.Number(0, 3))
|
||||
.Select(_ => f.Random.Char('a', 'z'))
|
||||
.ToArray());
|
||||
var digits = f.Random.String2(f.Random.Number(8, 10), "0123456789");
|
||||
return letters + digits;
|
||||
})
|
||||
.RuleFor(x => x.OCLCNumber, f =>
|
||||
{
|
||||
string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"];
|
||||
var prefix = f.Random.ArrayElement(prefixes);
|
||||
string number;
|
||||
switch (prefix)
|
||||
{
|
||||
case "ocm":
|
||||
number = f.Random.String2(8, "0123456789");
|
||||
break;
|
||||
case "ocn":
|
||||
number = f.Random.String2(f.Random.Number(9, 11), "0123456789");
|
||||
break;
|
||||
case "on":
|
||||
number = f.Random.String2(10, "0123456789");
|
||||
break;
|
||||
case "(OCoLC)":
|
||||
number = f.Random.String2(f.Random.Number(8, 10), "0123456789");
|
||||
break;
|
||||
default:
|
||||
number = f.Random.String2(f.Random.Number(8, 10), "0123456789");
|
||||
return number;
|
||||
}
|
||||
return prefix + number;
|
||||
})
|
||||
.RuleFor(x => x.OpenLibraryId, f =>
|
||||
{
|
||||
var firstDigit = f.Random.Number(1, 9);
|
||||
var remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789");
|
||||
var suffix = f.Random.ArrayElement(new[] { 'A', 'M', 'W' });
|
||||
return $"OL{firstDigit}{remainingDigits}{suffix}";
|
||||
})
|
||||
.RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50)))
|
||||
.RuleFor(x => x.GoogleBooksId, f =>
|
||||
{
|
||||
const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
return new string(Enumerable.Repeat(validChars, 12)
|
||||
.Select(s => s[f.Random.Number(validChars.Length - 1)])
|
||||
.ToArray());
|
||||
})
|
||||
.RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789"))
|
||||
.RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}")
|
||||
.RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}")
|
||||
.RuleFor(p => p.ISBNs, f => isbn.Generate(f.Random.Number(1, 5)))
|
||||
.RuleFor(p => p.Ratings, f => rating.Generate(f.Random.Number(1, 5)))
|
||||
.RuleFor(x => x.Contributors, f => mediaContributor.Generate(f.Random.Number(1, 5)));
|
||||
}
|
||||
|
||||
private void ConfigureCustomRequestTypes()
|
||||
{
|
||||
var releaseYear = _random.Next(2000, 2010);
|
||||
var reReleaseYear = _random.Next(2010, 2020);
|
||||
|
||||
_fixture.Register(() => new ReleaseInfoDto(
|
||||
_faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31)),
|
||||
releaseYear,
|
||||
_faker.DateOnlyBetween(new DateOnly(reReleaseYear, 1, 1), new DateOnly(reReleaseYear, 12, 31)),
|
||||
reReleaseYear,
|
||||
_fixture.Create<string>()[2..],
|
||||
_fixture.Create<string?>()));
|
||||
|
||||
_fixture.Register(() => new GenreDto(
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new TagDto(
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new LanguageInfoDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<string?>()
|
||||
));
|
||||
_fixture.Register(() => new IsbnDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<IsbnFormat>()
|
||||
));
|
||||
_fixture.Register(() => new BookRatingDto(
|
||||
_fixture.Create<decimal>(),
|
||||
_fixture.Create<decimal>(),
|
||||
_fixture.Create<BookRatingSource?>(),
|
||||
_fixture.Create<int?>()
|
||||
));
|
||||
_fixture.Register(() => new WrittenContentMetadataDto(
|
||||
_fixture.Create<string>()[255..],
|
||||
LimitStringLength(_fixture.Create<string?>(), 255),
|
||||
LimitStringLength(_fixture.Create<string?>(), 2000),
|
||||
_fixture.Create<ReleaseInfoDto>(),
|
||||
_fixture.Create<List<GenreDto>>(),
|
||||
_fixture.Create<List<TagDto>>(),
|
||||
_fixture.Create<LanguageInfoDto?>(),
|
||||
_fixture.Create<LanguageInfoDto?>(),
|
||||
_fixture.Create<string?>(),
|
||||
_fixture.Create<int?>()
|
||||
));
|
||||
_fixture.Register(() => new BookSeriesDto(
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new MediaContributorRoleDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<string>()
|
||||
));
|
||||
_fixture.Register(() => new MediaContributorDto(
|
||||
_fixture.Create<string>(),
|
||||
_fixture.Create<MediaContributorRoleDto>()
|
||||
));
|
||||
}
|
||||
|
||||
private static string? LimitStringLength(string? input, int maxLength)
|
||||
{
|
||||
return input?.Length > maxLength ? input[..maxLength] : input;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="4.18.1" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" />
|
||||
<PackageReference Include="Bogus" Version="35.6.0" />
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0" />
|
||||
<PackageReference Include="FluentAssertions" Version="6.12.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
|
||||
|
||||
Reference in new issue
Block a user