mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 09: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
+5
-8
@@ -1,6 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -8,7 +8,7 @@ using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BookContributorEntity"/> class.
|
||||
@@ -24,23 +24,20 @@ public class BookContributorEntityFixture
|
||||
/// <param name="id">Optional. The Id of the participation.</param>
|
||||
/// <param name="bookId">Optional. The Id of the book the contributor participated in.</param>
|
||||
/// <param name="mediaContributorId">Optional. The Id of the media contributor.</param>
|
||||
/// <param name="roleName">Optional. The display name of the role the contributor played in the book.</param>
|
||||
/// <param name="roleCategory">Optional. The canonical category of the role the contributor played in the book.</param>
|
||||
/// <param name="role">Optional. The role the contributor played in the book.</param>
|
||||
/// <returns>The created <see cref="BookContributorEntity"/>.</returns>
|
||||
public BookContributorEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? bookId = null,
|
||||
Guid? mediaContributorId = null,
|
||||
string? roleName = null,
|
||||
MediaContributorRoleCategory? roleCategory = null)
|
||||
MediaContributorRole? role = null)
|
||||
{
|
||||
return new BookContributorEntity
|
||||
{
|
||||
Id = id ?? Guid.NewGuid(),
|
||||
BookId = bookId ?? Guid.NewGuid(),
|
||||
MediaContributorId = mediaContributorId ?? Guid.NewGuid(),
|
||||
RoleName = roleName ?? _faker.Lorem.Word(),
|
||||
RoleCategory = roleCategory ?? _faker.PickRandom<MediaContributorRoleCategory>(),
|
||||
Role = role ?? MediaContributorRole.Author,
|
||||
CreatedOnUtc = _faker.Date.Past(),
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedOnUtc = null,
|
||||
+8
-7
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
@@ -11,6 +11,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
@@ -24,7 +25,7 @@ public class AddBookCommandFixture
|
||||
{
|
||||
private readonly IsbnDtoFixture _isbnDtoFixture = new();
|
||||
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
|
||||
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -53,7 +54,7 @@ public class AddBookCommandFixture
|
||||
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created command to add a book.</returns>
|
||||
public AddBookCommand Create(
|
||||
Guid? libraryId = null,
|
||||
string? libraryId = null,
|
||||
string? path = null,
|
||||
WrittenContentMetadataDto? metadata = null,
|
||||
BookFormat? format = null,
|
||||
@@ -70,7 +71,7 @@ public class AddBookCommandFixture
|
||||
string? barnesAndNobleId = null,
|
||||
string? appleBooksId = null,
|
||||
List<IsbnDto>? isbns = null,
|
||||
List<MediaContributorDto>? contributors = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<BookRatingDto>? ratings = null,
|
||||
bool includeMetadata = true,
|
||||
bool includeOptionalProperties = true)
|
||||
@@ -97,8 +98,8 @@ public class AddBookCommandFixture
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
|
||||
.RuleFor(x => x.Path, f => path ?? f.System.FilePath())
|
||||
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid().ToString())
|
||||
.RuleFor(x => x.Path, f => path ?? Path.Combine(Path.GetTempPath(), "lumina-books", f.System.FileName()))
|
||||
.RuleFor(x => x.Metadata, includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null)
|
||||
.RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom<BookFormat>() : null))
|
||||
.RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
|
||||
@@ -115,7 +116,7 @@ public class AddBookCommandFixture
|
||||
.RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null))
|
||||
.RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
|
||||
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
|
||||
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
|
||||
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-12
@@ -21,35 +21,27 @@ public class MediaContributorDtoFixture
|
||||
/// Creates a random valid <see cref="MediaContributorDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="displayName">Optional. The display name of the media contributor.</param>
|
||||
/// <param name="roleName">Optional. The name of the role assigned to the media contributor.</param>
|
||||
/// <param name="roleCategory">Optional. The category of the role.</param>
|
||||
/// <param name="role">Optional. The canonical role assigned to the media contributor.</param>
|
||||
/// <param name="legalName">Optional. The legal name of the media contributor.</param>
|
||||
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeDisplayName">Whether the display name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLegalName">Whether the legal name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRole">Whether the role should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRoleName">Whether the role name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeRoleCategory">Whether the role category should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="MediaContributorDto"/>.</returns>
|
||||
public MediaContributorDto Create(
|
||||
string? displayName = null,
|
||||
string? roleName = null,
|
||||
MediaContributorRoleCategory? roleCategory = null,
|
||||
MediaContributorRole? role = null,
|
||||
string? legalName = null,
|
||||
bool includeName = true,
|
||||
bool includeDisplayName = true,
|
||||
bool includeLegalName = true,
|
||||
bool includeRole = true,
|
||||
bool includeRoleName = true,
|
||||
bool includeRoleCategory = true)
|
||||
bool includeRole = true)
|
||||
{
|
||||
return new MediaContributorDto(
|
||||
Name: includeName ? new MediaContributorNameDto(
|
||||
DisplayName: includeDisplayName ? displayName ?? _faker.Name.FullName() : null,
|
||||
LegalName: includeLegalName ? legalName : null) : null,
|
||||
Role: includeRole ? new MediaContributorRoleDto(
|
||||
Name: includeRoleName ? roleName ?? _faker.Commerce.Department() : null,
|
||||
Category: includeRoleCategory ? roleCategory ?? _faker.PickRandom<MediaContributorRoleCategory>() : null) : null);
|
||||
Role: includeRole ? role ?? _faker.PickRandom<MediaContributorRole>() : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaContributorReferenceDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorReferenceDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MediaContributorReferenceDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="contributorId">Optional. The Id of the media contributor.</param>
|
||||
/// <param name="role">Optional. The role the contributor played.</param>
|
||||
/// <returns>The created <see cref="MediaContributorReferenceDto"/>.</returns>
|
||||
public MediaContributorReferenceDto Create(Guid? contributorId = null, MediaContributorRole? role = null)
|
||||
{
|
||||
return new MediaContributorReferenceDto(
|
||||
ContributorId: contributorId ?? Guid.NewGuid(),
|
||||
Role: role ?? _faker.PickRandom<MediaContributorRole>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="MediaContributorReferenceDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<MediaContributorReferenceDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaContributorRoleDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorRoleDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MediaContributorRoleDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The name of the role assigned to the media contributor.</param>
|
||||
/// <param name="category">Optional. The category of the role.</param>
|
||||
/// <returns>The created <see cref="MediaContributorRoleDto"/>.</returns>
|
||||
public MediaContributorRoleDto Create(
|
||||
string? name = null,
|
||||
MediaContributorRoleCategory? category = null)
|
||||
{
|
||||
return new MediaContributorRoleDto(
|
||||
name ?? _faker.Commerce.Department(),
|
||||
category ?? _faker.PickRandom<MediaContributorRoleCategory>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="MediaContributorRoleDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<MediaContributorRoleDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+6
-9
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
@@ -11,6 +11,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
@@ -24,13 +25,12 @@ public class AddBookRequestFixture
|
||||
{
|
||||
private readonly IsbnDtoFixture _isbnDtoFixture = new();
|
||||
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
|
||||
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid request to add a book.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">Optional. The file system path of the book.</param>
|
||||
/// <param name="metadata">Optional. The written content metadata of the book.</param>
|
||||
/// <param name="format">Optional. The format of the book.</param>
|
||||
@@ -52,7 +52,6 @@ public class AddBookRequestFixture
|
||||
/// <param name="includeOptionalProperties">Whether the properties that are not explicitly provided should be randomized, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created request to add a book.</returns>
|
||||
public AddBookRequest Create(
|
||||
Guid? libraryId = null,
|
||||
string? path = null,
|
||||
WrittenContentMetadataDto? metadata = null,
|
||||
BookFormat? format = null,
|
||||
@@ -69,13 +68,12 @@ public class AddBookRequestFixture
|
||||
string? barnesAndNobleId = null,
|
||||
string? appleBooksId = null,
|
||||
List<IsbnDto>? isbns = null,
|
||||
List<MediaContributorDto>? contributors = null,
|
||||
List<MediaContributorReferenceDto>? contributors = null,
|
||||
List<BookRatingDto>? ratings = null,
|
||||
bool includeOptionalProperties = true)
|
||||
{
|
||||
return new Faker<AddBookRequest>()
|
||||
.CustomInstantiator(f => new AddBookRequest(
|
||||
default,
|
||||
default!,
|
||||
default!,
|
||||
default,
|
||||
@@ -95,8 +93,7 @@ public class AddBookRequestFixture
|
||||
default!,
|
||||
default!
|
||||
))
|
||||
.RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
|
||||
.RuleFor(x => x.Path, f => path ?? f.System.FilePath())
|
||||
.RuleFor(x => x.Path, f => path ?? Path.Combine(Path.GetTempPath(), "lumina-books", f.System.FileName()))
|
||||
.RuleFor(x => x.Metadata, metadata ?? _writtenContentMetadataDtoFixture.Create())
|
||||
.RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom<BookFormat>() : null))
|
||||
.RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null))
|
||||
@@ -113,7 +110,7 @@ public class AddBookRequestFixture
|
||||
.RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null))
|
||||
.RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
|
||||
.RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null))
|
||||
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
|
||||
.RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+2
-2
@@ -24,7 +24,7 @@ public class BookResponseFixture
|
||||
private readonly Faker _faker = new();
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
private readonly IsbnDtoFixture _isbnDtoFixture = new();
|
||||
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
|
||||
private readonly BookSeriesDtoFixture _bookSeriesDtoFixture = new();
|
||||
|
||||
@@ -70,7 +70,7 @@ public class BookResponseFixture
|
||||
_faker.Random.AlphaNumeric(10),
|
||||
_faker.Random.AlphaNumeric(8),
|
||||
_isbnDtoFixture.CreateMany(1),
|
||||
_mediaContributorDtoFixture.CreateMany(1),
|
||||
_mediaContributorReferenceDtoFixture.CreateMany(1),
|
||||
_bookRatingDtoFixture.CreateMany(1),
|
||||
metadataStatus ?? _faker.PickRandom<MetadataStatus>(),
|
||||
_faker.Date.Recent().ToUniversalTime(),
|
||||
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaContributorRole"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorRoleFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MediaContributorRole"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The name of the role. If not provided, a random name is generated.</param>
|
||||
/// <param name="category">Optional. The category of the role. If not provided, a random category is generated.</param>
|
||||
/// <returns>The created <see cref="MediaContributorRole"/>.</returns>
|
||||
public MediaContributorRole Create(string? name = null, MediaContributorRoleCategory? category = null)
|
||||
{
|
||||
return MediaContributorRole.Create(
|
||||
name ?? _faker.Lorem.Word(),
|
||||
category ?? _faker.PickRandom<MediaContributorRoleCategory>()).Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MediaContributorRole"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MediaContributorRole"/> instances.</returns>
|
||||
public List<MediaContributorRole> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+4
-5
@@ -1,14 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -27,7 +27,6 @@ public class BookFixture
|
||||
private readonly WrittenContentMetadataFixture _writtenContentMetadataFixture = new();
|
||||
private readonly IsbnFixture _isbnFixture = new();
|
||||
private readonly BookRatingFixture _bookRatingFixture = new();
|
||||
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="Book"/> domain aggregate.
|
||||
@@ -70,7 +69,7 @@ public class BookFixture
|
||||
string? barnesAndNobleId = null,
|
||||
string? appleBooksId = null,
|
||||
List<Isbn>? isbns = null,
|
||||
List<MediaContributorId>? contributors = null,
|
||||
List<BookMediaContributor>? contributors = null,
|
||||
List<BookRating>? ratings = null)
|
||||
{
|
||||
return Book.Create(
|
||||
@@ -91,7 +90,7 @@ public class BookFixture
|
||||
barnesAndNobleId is null ? Optional<string>.Some(_faker.Random.String2(10, "0123456789")) : Optional<string>.Some(barnesAndNobleId),
|
||||
appleBooksId is null ? Optional<string>.Some($"id{_faker.Random.Number(1, 999999)}") : Optional<string>.Some(appleBooksId),
|
||||
isbns ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _isbnFixture.Create())],
|
||||
contributors ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _mediaContributorIdFixture.Create())],
|
||||
contributors ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => BookMediaContributor.Create(MediaContributorId.CreateUnique(), MediaContributorRole.Author).Value)],
|
||||
ratings ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _bookRatingFixture.Create())]
|
||||
).Value;
|
||||
}
|
||||
|
||||
+4
-11
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.MediaContributors;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaContributors;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -14,7 +15,6 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorDtoFixture
|
||||
{
|
||||
private static readonly string[] RoleCategories = ["Author", "Translator", "Illustrator", "Editor", "Narrator"];
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -22,16 +22,13 @@ public class MediaContributorDtoFixture
|
||||
/// </summary>
|
||||
/// <param name="displayName">Optional. The name by which the contributor is popularly known.</param>
|
||||
/// <param name="legalName">Optional. The legal name of the contributor.</param>
|
||||
/// <param name="roleName">Optional. The name of the role of the contributor.</param>
|
||||
/// <param name="roleCategory">Optional. The category of the role of the contributor.</param>
|
||||
/// <param name="role">Optional. The canonical role of the contributor.</param>
|
||||
/// <returns>A configured <see cref="MediaContributorDto"/> instance.</returns>
|
||||
public MediaContributorDto Create(
|
||||
string? displayName = null,
|
||||
string? legalName = null,
|
||||
string? roleName = null,
|
||||
string? roleCategory = null)
|
||||
MediaContributorRole? role = null)
|
||||
{
|
||||
string resolvedRoleCategory = roleCategory ?? _faker.Random.ArrayElement(RoleCategories);
|
||||
return new MediaContributorDto
|
||||
{
|
||||
Name = new MediaContributorNameDto
|
||||
@@ -39,11 +36,7 @@ public class MediaContributorDtoFixture
|
||||
DisplayName = displayName ?? _faker.Name.FullName(),
|
||||
LegalName = legalName ?? _faker.Name.FullName()
|
||||
},
|
||||
Role = new MediaContributorRoleDto
|
||||
{
|
||||
Name = roleName ?? resolvedRoleCategory.ToLowerInvariant(),
|
||||
Category = resolvedRoleCategory
|
||||
}
|
||||
Role = role ?? MediaContributorRole.Author
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+55
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Books;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -135,4 +136,58 @@ public class BookRepositoryTests
|
||||
Assert.NotNull(keptArtwork);
|
||||
Assert.Equal(ArtworkStatus.Enriched, keptArtwork!.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenCalledWithAValidBook_ShouldPersistTheBook()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(book, CancellationToken.None);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Created, result.Value);
|
||||
BookEntity? storedBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == book.Id);
|
||||
Assert.NotNull(storedBook);
|
||||
Assert.Equal(book.Path, storedBook!.Path);
|
||||
Assert.Equal(book.Title, storedBook.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertAsync_WhenAnotherBookOfTheSameLibraryHasTheSamePath_ShouldReturnBookAlreadyExists()
|
||||
{
|
||||
// Arrange
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity existingBook = _bookEntityFixture.Create();
|
||||
existingBook.LibraryId = libraryId;
|
||||
existingBook.Path = "/books/existing.epub";
|
||||
context.Books.Add(existingBook);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
book.Path = "/books/existing.epub";
|
||||
|
||||
// Act
|
||||
Result<Created> result = await sut.InsertAsync(book, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError);
|
||||
}
|
||||
}
|
||||
+564
-114
@@ -1,7 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
@@ -23,6 +26,7 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
@@ -59,8 +63,10 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
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();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly string _libraryContentLocation = Path.GetTempPath();
|
||||
private Guid _libraryId;
|
||||
|
||||
/// <summary>
|
||||
@@ -85,7 +91,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = dbContext.Users.Single(user => user.Username == _apiFactory.TestUsername).Id;
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: _libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: _libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [_libraryContentLocation]));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
@@ -187,7 +193,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
// check Location header
|
||||
Assert.NotNull(response.Headers.Location);
|
||||
string locationUri = response.Headers.Location!.ToString();
|
||||
Assert.EndsWith("/api/v1/books/" + bookResponse.Id.Value, locationUri);
|
||||
Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id.Value}", locationUri);
|
||||
|
||||
// extract ID from Location header and compare
|
||||
string idFromHeader = locationUri.Split('/').Last();
|
||||
@@ -1107,130 +1113,39 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
public async Task AddBook_WhenCalledWithNullContributors_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(includeOptionalProperties: false);
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create() with { Contributors = null };
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorsListCannotBeNull.Description);
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.ContributorsListCannotBeNull.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithNullContributorName_ShouldReturnUnprocessableEntity()
|
||||
public async Task AddBook_WhenCalledWithEmptyContributorId_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(roleName: "author", roleCategory: MediaContributorRoleCategory.Author, includeName: false)]);
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorNameCannotBeEmpty.Description);
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.MediaContributorIdCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithEmptyContributorDisplayName_ShouldReturnUnprocessableEntity()
|
||||
public async Task AddBook_WhenCalledWithInvalidContributorRole_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]);
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithNullContributorDisplayName_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(includeDisplayName: false, includeLegalName: false, roleName: "author", roleCategory: MediaContributorRoleCategory.Author)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithInvalidLengthContributorDisplayName_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(150))]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithInvalidLengthContributorLegalName_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), legalName: new Faker().Random.String2(150), roleName: "author", roleCategory: MediaContributorRoleCategory.Author)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithEmptyContributorRole_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), includeRole: false)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorRoleCannotBeNull.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithEmptyContributorRoleName_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), includeRoleName: false, roleCategory: MediaContributorRoleCategory.Author)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleNameCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleName_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), roleName: new Faker().Random.String2(100), roleCategory: MediaContributorRoleCategory.Author)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithEmptyContributorRoleCategory_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(50), roleName: "author", includeRoleCategory: false)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description);
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.UnknownMediaContributorRole.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -1304,13 +1219,14 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenTwoContributorsShareTheSameDisplayName_ShouldCreateOneContributorWithTwoBookLinks()
|
||||
public async Task AddBook_WhenTwoContributorsHaveTheSameIdWithDifferentRoles_ShouldCreateTwoBookLinks()
|
||||
{
|
||||
// Arrange
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors:
|
||||
[
|
||||
_mediaContributorDtoFixture.Create(displayName: "Duplicated Author", legalName: "Duplicated Author Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author),
|
||||
_mediaContributorDtoFixture.Create(displayName: "Duplicated Author", legalName: "Duplicated Author Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator)
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author),
|
||||
_mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator)
|
||||
]);
|
||||
|
||||
// Act
|
||||
@@ -1324,15 +1240,518 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaContributorEntity contributor = dbContext.MediaContributors.Single(mediaContributor => mediaContributor.DisplayName == "Duplicated Author");
|
||||
List<BookContributorEntity> links = [.. dbContext.Books
|
||||
.Include(book => book.BookContributors)
|
||||
.Single(book => book.Id == bookResponse!.Id.Value)
|
||||
.BookContributors];
|
||||
Assert.Equal(2, links.Count);
|
||||
Assert.All(links, link => Assert.Equal(contributor.Id, link.MediaContributorId));
|
||||
Assert.Contains(links, link => link.RoleName == "author");
|
||||
Assert.Contains(links, link => link.RoleName == "illustrator");
|
||||
Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId));
|
||||
Assert.Contains(links, link => link.Role == MediaContributorRole.Author);
|
||||
Assert.Contains(links, link => link.Role == MediaContributorRole.Illustrator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenBookPathIsNotWithinTheLibraryContentLocations_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string pathOutsideTheLibrary = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "..", "lumina-books-outside", $"{Guid.NewGuid():N}.epub"));
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(path: pathOutsideTheLibrary);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.BookPathMustBeWithinLibraryContentLocations.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenBookPathAlreadyExistsInTheLibrary_ShouldReturnConflict()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await PostBookAsync(bookRequest);
|
||||
HttpResponseMessage secondResponse = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Created, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Conflict, secondResponse.StatusCode);
|
||||
Assert.Equal("application/problem+json", secondResponse.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await secondResponse.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status409Conflict, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(Errors.WrittenContent.BookAlreadyExists.Description, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenAReferencedContributorDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookWithoutSeedingContributorsAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(Errors.MediaContributor.MediaContributorNotFound.Description, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithTooLongPath_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".epub");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.BookPathMustBeMaximum2048CharactersLong.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenTheLibraryDoesNotExist_ShouldReturnNotFound()
|
||||
{
|
||||
// Arrange
|
||||
// only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
Guid missingLibraryId = Guid.NewGuid();
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.PostAsJsonAsync($"/api/v1/libraries/{missingLibraryId}/books", bookRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(Errors.Library.LibraryNotFound.Description, problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenTitleIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200)));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenOriginalTitleIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenDescriptionIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenOriginalReleaseYearIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false)));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenReReleaseYearIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: new Faker().Random.Int(2000, 2005), reReleaseYear: new Faker().Random.Int(2005, 2010), includeReReleaseDate: false)));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenReleaseVersionIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenGenresAreValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenTagsAreValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidPublisher_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100)));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenPageCountIsPositive_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenFormatIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(format: BookFormat.Hardcover);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenEditionIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(edition: new Faker().Random.String2(50));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenVolumeNumberIsPositive_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(volumeNumber: 1);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenAsinIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(asin: new Faker().Random.String2(10));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenGoodreadsIdIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(goodreadsId: "123456789");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenLccnIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(lccn: "n78890351");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidOclcNumberFormat1_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "ocm12345678");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidOclcNumberFormat2_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "ocn123456789");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidOclcNumberFormat3_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "on1234567890");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidOclcNumberFormat4_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "(OCoLC)1234567890");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidOclcNumberFormat5_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(oclcNumber: "12345678");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenOpenLibraryIdIsValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(openLibraryId: "OL123456M");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidLibraryThingId_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(libraryThingId: new Faker().Random.String2(50));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidGoogleBooksId_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidBarnesAndNobleId_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidAppleBooksId_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(appleBooksId: "id123456");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidIsbn10_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidIsbn13_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenContributorsAreValid_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithValidRatings_ShouldAddBook()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/not-a-guid/books", bookRequest);
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id becomes an empty Guid in the command mapping and the
|
||||
// command validator reports a clean validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1340,9 +1759,40 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
/// </summary>
|
||||
/// <param name="request">The request to post.</param>
|
||||
/// <returns>The HTTP response of the POST request.</returns>
|
||||
private Task<HttpResponseMessage> PostBookAsync(AddBookRequest request)
|
||||
private async Task<HttpResponseMessage> PostBookAsync(AddBookRequest request)
|
||||
{
|
||||
return _client.PostAsJsonAsync("/api/v1/books", request with { LibraryId = _libraryId });
|
||||
await SeedContributorsAsync(request.Contributors);
|
||||
return await _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", request);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Posts a request to add a book to the media library owned by the authenticated user of the current test, without seeding the contributors it references.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to post.</param>
|
||||
/// <returns>The HTTP response of the POST request.</returns>
|
||||
private Task<HttpResponseMessage> PostBookWithoutSeedingContributorsAsync(AddBookRequest request)
|
||||
{
|
||||
return _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", request);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the media contributors referenced by the provided book contributors, so that the handler finds them already existing.
|
||||
/// </summary>
|
||||
/// <param name="contributors">The contributors of the book request.</param>
|
||||
private async Task SeedContributorsAsync(List<MediaContributorReferenceDto>? contributors)
|
||||
{
|
||||
if (contributors is null || contributors.Count == 0)
|
||||
return;
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
foreach (Guid contributorId in contributors.Select(contributor => contributor.ContributorId).Distinct())
|
||||
{
|
||||
if (contributorId == Guid.Empty || await dbContext.MediaContributors.AnyAsync(contributor => contributor.Id == contributorId))
|
||||
continue;
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()));
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, params string[] expectedErrorCodes)
|
||||
@@ -1355,7 +1805,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/books", problemDetails["instance"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{_libraryId}/books", problemDetails["instance"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
@@ -1383,4 +1833,4 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
+136
-4
@@ -1,15 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
@@ -26,7 +30,10 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo
|
||||
public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly AddBookRequestFixture _addBookRequestFixture = new();
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -39,6 +46,59 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
public AddBookEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookRequest request = _addBookRequestFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{libraryId}/books", problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
|
||||
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
AddBookRequest request = _addBookRequestFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(requesterUsername);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -50,11 +110,18 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, userId);
|
||||
AddBookRequest request = _addBookRequestFixture.Create(libraryId: libraryId, path: maliciousPath);
|
||||
string contentLocation = Path.GetTempPath();
|
||||
string injectedPath = Path.Combine(contentLocation, $"{maliciousPath}.epub");
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [contentLocation]));
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
AddBookRequest request = _addBookRequestFixture.Create(path: injectedPath, contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/books", request);
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
|
||||
|
||||
// Assert
|
||||
// the malicious path passes the authenticated handler, reaches the parameterized insert, and is persisted
|
||||
@@ -71,6 +138,71 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task AddBook_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string contentLocation = Path.GetTempPath();
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [contentLocation]));
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
string bookPath = Path.Combine(contentLocation, $"{Guid.NewGuid()}.epub");
|
||||
AddBookRequest request = _addBookRequestFixture.Create(path: bookPath, metadata: _writtenContentMetadataDtoFixture.Create(title: maliciousTitle), contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
|
||||
|
||||
// Assert
|
||||
// the malicious title passes the authenticated handler, reaches the parameterized insert, and is persisted
|
||||
// verbatim: if it were concatenated into raw SQL, the insert would fail and the book would not be created
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
BookEntity storedBook = await dbContext.Books.SingleAsync(book => book.LibraryId == libraryId);
|
||||
Assert.Equal(maliciousTitle, storedBook.Title);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task AddBook_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
AddBookRequest request = _addBookRequestFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books", request);
|
||||
|
||||
// Assert
|
||||
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command
|
||||
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
|
||||
// or the injected payload.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
|
||||
+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