mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 22:11:10 +00:00
Refactors the book, artist, and album slices across the stack
This commit is contained in:
1 parent
8aaf9fe64e
commit
ea6eb9f796
439 files changed
+28235
-3156
No files matched your search
+5
-2
@@ -19,19 +19,22 @@ public class UpdateBookCoverCommandFixture
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="UpdateBookCoverCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the book belongs to.</param>
|
||||
/// <param name="bookId">Optional. The Id of the book whose cover is updated.</param>
|
||||
/// <param name="cover">Optional. The stream of the uploaded cover image file.</param>
|
||||
/// <param name="fileName">Optional. The name of the uploaded cover image file.</param>
|
||||
/// <param name="includeCover">Whether the cover stream should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="UpdateBookCoverCommand"/>.</returns>
|
||||
public UpdateBookCoverCommand Create(
|
||||
Guid? bookId = null,
|
||||
string? libraryId = null,
|
||||
string? bookId = null,
|
||||
Stream? cover = null,
|
||||
string? fileName = null,
|
||||
bool includeCover = true)
|
||||
{
|
||||
return new UpdateBookCoverCommand(
|
||||
bookId ?? Guid.NewGuid(),
|
||||
libraryId ?? Guid.NewGuid().ToString(),
|
||||
bookId ?? Guid.NewGuid().ToString(),
|
||||
includeCover ? (cover ?? CreateCoverStream()) : null,
|
||||
fileName ?? "cover.jpg"
|
||||
);
|
||||
|
||||
+4
-2
@@ -17,12 +17,14 @@ public class GetReadingAvailabilityQueryFixture
|
||||
/// <summary>
|
||||
/// Creates a random valid query to check the reading availability of a book.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the library the book belongs to.</param>
|
||||
/// <param name="bookId">Optional. The Id of the book whose reading availability is checked.</param>
|
||||
/// <returns>The created <see cref="GetReadingAvailabilityQuery"/>.</returns>
|
||||
public GetReadingAvailabilityQuery Create(
|
||||
Guid? bookId = null)
|
||||
string? libraryId = null,
|
||||
string? bookId = null)
|
||||
{
|
||||
return new GetReadingAvailabilityQuery(bookId ?? Guid.NewGuid());
|
||||
return new GetReadingAvailabilityQuery(libraryId ?? Guid.NewGuid().ToString(), bookId ?? Guid.NewGuid().ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-2
@@ -17,12 +17,14 @@ public class GetReadingManifestQueryFixture
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get the reading manifest of a book.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the library the book belongs to.</param>
|
||||
/// <param name="bookId">Optional. The Id of the book whose reading manifest is retrieved.</param>
|
||||
/// <returns>The created <see cref="GetReadingManifestQuery"/>.</returns>
|
||||
public GetReadingManifestQuery Create(
|
||||
Guid? bookId = null)
|
||||
string? libraryId = null,
|
||||
string? bookId = null)
|
||||
{
|
||||
return new GetReadingManifestQuery(bookId ?? Guid.NewGuid());
|
||||
return new GetReadingManifestQuery(libraryId ?? Guid.NewGuid().ToString(), bookId ?? Guid.NewGuid().ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-2
@@ -17,14 +17,16 @@ public class GetReadingResourceQueryFixture
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get a resource of a book.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the library the book belongs to.</param>
|
||||
/// <param name="bookId">Optional. The Id of the book whose resource is retrieved.</param>
|
||||
/// <param name="resourceKey">Optional. The opaque resource key of the resource.</param>
|
||||
/// <returns>The created <see cref="GetReadingResourceQuery"/>.</returns>
|
||||
public GetReadingResourceQuery Create(
|
||||
Guid? bookId = null,
|
||||
string? libraryId = null,
|
||||
string? bookId = null,
|
||||
string? resourceKey = null)
|
||||
{
|
||||
return new GetReadingResourceQuery(bookId ?? Guid.NewGuid(), resourceKey ?? $"resource-{Guid.NewGuid():N}");
|
||||
return new GetReadingResourceQuery(libraryId ?? Guid.NewGuid().ToString(), bookId ?? Guid.NewGuid().ToString(), resourceKey ?? $"resource-{Guid.NewGuid():N}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-2
@@ -17,14 +17,16 @@ public class GetReadingSectionQueryFixture
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get the content of a reading section of a book.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the library the book belongs to.</param>
|
||||
/// <param name="bookId">Optional. The Id of the book whose reading section is retrieved.</param>
|
||||
/// <param name="locationRef">Optional. The opaque location reference of the reading section.</param>
|
||||
/// <returns>The created <see cref="GetReadingSectionQuery"/>.</returns>
|
||||
public GetReadingSectionQuery Create(
|
||||
Guid? bookId = null,
|
||||
string? libraryId = null,
|
||||
string? bookId = null,
|
||||
string? locationRef = null)
|
||||
{
|
||||
return new GetReadingSectionQuery(bookId ?? Guid.NewGuid(), locationRef ?? $"section-{Guid.NewGuid():N}");
|
||||
return new GetReadingSectionQuery(libraryId ?? Guid.NewGuid().ToString(), bookId ?? Guid.NewGuid().ToString(), locationRef ?? $"section-{Guid.NewGuid():N}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetReadingAvailabilityRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingAvailabilityRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetReadingAvailabilityRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">Optional. The Id of the book whose reading availability is checked.</param>
|
||||
/// <returns>The created <see cref="GetReadingAvailabilityRequest"/>.</returns>
|
||||
public GetReadingAvailabilityRequest Create(
|
||||
Guid? bookId = null)
|
||||
{
|
||||
return new GetReadingAvailabilityRequest(bookId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetReadingAvailabilityRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<GetReadingAvailabilityRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetReadingManifestRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingManifestRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetReadingManifestRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">Optional. The Id of the book whose reading manifest is retrieved.</param>
|
||||
/// <returns>The created <see cref="GetReadingManifestRequest"/>.</returns>
|
||||
public GetReadingManifestRequest Create(
|
||||
Guid? bookId = null)
|
||||
{
|
||||
return new GetReadingManifestRequest(bookId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetReadingManifestRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<GetReadingManifestRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetReadingResourceRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingResourceRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetReadingResourceRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">Optional. The Id of the book whose resource is retrieved.</param>
|
||||
/// <param name="resourceKey">Optional. The opaque resource key of the resource.</param>
|
||||
/// <returns>The created <see cref="GetReadingResourceRequest"/>.</returns>
|
||||
public GetReadingResourceRequest Create(
|
||||
Guid? bookId = null,
|
||||
string? resourceKey = null)
|
||||
{
|
||||
return new GetReadingResourceRequest(bookId ?? Guid.NewGuid(), resourceKey ?? $"resource-{Guid.NewGuid():N}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetReadingResourceRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<GetReadingResourceRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetReadingSectionRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingSectionRequestFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetReadingSectionRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">Optional. The Id of the book whose reading section is retrieved.</param>
|
||||
/// <param name="locationRef">Optional. The opaque location reference of the reading section.</param>
|
||||
/// <returns>The created <see cref="GetReadingSectionRequest"/>.</returns>
|
||||
public GetReadingSectionRequest Create(
|
||||
Guid? bookId = null,
|
||||
string? locationRef = null)
|
||||
{
|
||||
return new GetReadingSectionRequest(bookId ?? Guid.NewGuid(), locationRef ?? $"section-{Guid.NewGuid():N}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetReadingSectionRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<GetReadingSectionRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="UpdateBookCoverResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookCoverResponseFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="UpdateBookCoverResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="coverPath">Optional. The relative path of the stored cover image.</param>
|
||||
/// <returns>The created <see cref="UpdateBookCoverResponse"/>.</returns>
|
||||
public UpdateBookCoverResponse Create(string? coverPath = null)
|
||||
{
|
||||
return new UpdateBookCoverResponse(
|
||||
coverPath ?? _faker.System.FilePath()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="UpdateBookCoverResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="count">The number of elements to create.</param>
|
||||
/// <returns>The created list.</returns>
|
||||
public List<UpdateBookCoverResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BookLibraryId"/> domain value object.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookLibraryIdFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="BookLibraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">Optional. The value used to create the <see cref="BookLibraryId"/>. If not provided, a random value is generated.</param>
|
||||
/// <returns>The created <see cref="BookLibraryId"/>.</returns>
|
||||
public BookLibraryId Create(Guid? value = null)
|
||||
{
|
||||
return value is null ? BookLibraryId.CreateUnique().Value : BookLibraryId.Create(value.Value).Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="BookLibraryId"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="BookLibraryId"/> instances.</returns>
|
||||
public List<BookLibraryId> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="UpdateBookCoverDto"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookCoverDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="UpdateBookCoverDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="coverPath">Optional. The relative path of the stored cover image.</param>
|
||||
/// <returns>A configured <see cref="UpdateBookCoverDto"/> instance.</returns>
|
||||
public UpdateBookCoverDto Create(string? coverPath = null)
|
||||
{
|
||||
return new UpdateBookCoverDto
|
||||
{
|
||||
CoverPath = coverPath ?? _faker.System.FilePath()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="UpdateBookCoverDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="UpdateBookCoverDto"/> instances.</returns>
|
||||
public List<UpdateBookCoverDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -18,11 +18,13 @@ public class GetBookRequestFixture
|
||||
/// Creates a new <see cref="GetBookRequest"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional unique identifier of the book to retrieve.</param>
|
||||
/// <param name="libraryId">Optional unique identifier of the media library the book belongs to.</param>
|
||||
/// <returns>A configured <see cref="GetBookRequest"/> instance.</returns>
|
||||
public GetBookRequest Create(
|
||||
Guid? id = null)
|
||||
Guid? id = null,
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new GetBookRequest(id?.ToString() ?? Guid.NewGuid().ToString());
|
||||
return new GetBookRequest(id?.ToString() ?? Guid.NewGuid().ToString(), libraryId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-2
@@ -18,11 +18,13 @@ public class GetBookReadingAvailabilityRequestFixture
|
||||
/// Creates a random valid <see cref="GetBookReadingAvailabilityRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">Optional. The Id of the book whose reading availability is checked.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the book belongs to.</param>
|
||||
/// <returns>The created <see cref="GetBookReadingAvailabilityRequest"/>.</returns>
|
||||
public GetBookReadingAvailabilityRequest Create(
|
||||
Guid? bookId = null)
|
||||
Guid? bookId = null,
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new GetBookReadingAvailabilityRequest(bookId ?? Guid.NewGuid());
|
||||
return new GetBookReadingAvailabilityRequest(bookId ?? Guid.NewGuid(), libraryId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-2
@@ -18,11 +18,13 @@ public class GetBookReadingManifestRequestFixture
|
||||
/// Creates a random valid <see cref="GetBookReadingManifestRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">Optional. The Id of the book whose reading manifest is retrieved.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the book belongs to.</param>
|
||||
/// <returns>The created <see cref="GetBookReadingManifestRequest"/>.</returns>
|
||||
public GetBookReadingManifestRequest Create(
|
||||
Guid? bookId = null)
|
||||
Guid? bookId = null,
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new GetBookReadingManifestRequest(bookId ?? Guid.NewGuid());
|
||||
return new GetBookReadingManifestRequest(bookId ?? Guid.NewGuid(), libraryId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-2
@@ -19,12 +19,14 @@ public class GetBookReadingResourceRequestFixture
|
||||
/// </summary>
|
||||
/// <param name="bookId">Optional. The Id of the book whose resource is retrieved.</param>
|
||||
/// <param name="resourceKey">Optional. The opaque resource key of the resource.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the book belongs to.</param>
|
||||
/// <returns>The created <see cref="GetBookReadingResourceRequest"/>.</returns>
|
||||
public GetBookReadingResourceRequest Create(
|
||||
Guid? bookId = null,
|
||||
string? resourceKey = null)
|
||||
string? resourceKey = null,
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new GetBookReadingResourceRequest(bookId ?? Guid.NewGuid(), resourceKey ?? $"resource-{Guid.NewGuid():N}");
|
||||
return new GetBookReadingResourceRequest(bookId ?? Guid.NewGuid(), resourceKey ?? $"resource-{Guid.NewGuid():N}", libraryId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-2
@@ -19,12 +19,14 @@ public class GetBookReadingSectionRequestFixture
|
||||
/// </summary>
|
||||
/// <param name="bookId">Optional. The Id of the book whose reading section is retrieved.</param>
|
||||
/// <param name="locationRef">Optional. The opaque location reference of the reading section.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the book belongs to.</param>
|
||||
/// <returns>The created <see cref="GetBookReadingSectionRequest"/>.</returns>
|
||||
public GetBookReadingSectionRequest Create(
|
||||
Guid? bookId = null,
|
||||
string? locationRef = null)
|
||||
string? locationRef = null,
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new GetBookReadingSectionRequest(bookId ?? Guid.NewGuid(), locationRef ?? $"section-{Guid.NewGuid():N}");
|
||||
return new GetBookReadingSectionRequest(bookId ?? Guid.NewGuid(), locationRef ?? $"section-{Guid.NewGuid():N}", libraryId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-2
@@ -18,11 +18,13 @@ public class ReadBookViewRequestFixture
|
||||
/// Creates a random valid <see cref="ReadBookViewRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">Optional. The Id of the book to read.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library the book belongs to.</param>
|
||||
/// <returns>The created <see cref="ReadBookViewRequest"/>.</returns>
|
||||
public ReadBookViewRequest Create(
|
||||
Guid? bookId = null)
|
||||
Guid? bookId = null,
|
||||
Guid? libraryId = null)
|
||||
{
|
||||
return new ReadBookViewRequest(bookId ?? Guid.NewGuid());
|
||||
return new ReadBookViewRequest(bookId ?? Guid.NewGuid(), libraryId ?? Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+8
-8
@@ -1,7 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Books;
|
||||
using Lumina.DataAccess.Core.Repositories.BookLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -16,7 +16,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Books;
|
||||
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.BookLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="BookRepository"/> class, exercising it against a real SQLite database.
|
||||
@@ -43,12 +43,12 @@ public class BookRepositoryTests
|
||||
changedBook.LibraryId = libraryId;
|
||||
changedBook.Path = "/books/changed.epub";
|
||||
changedBook.MetadataStatus = MetadataStatus.Enriched;
|
||||
changedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
changedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
BookEntity unchangedBook = _bookEntityFixture.Create();
|
||||
unchangedBook.LibraryId = libraryId;
|
||||
unchangedBook.Path = "/books/unchanged.epub";
|
||||
unchangedBook.MetadataStatus = MetadataStatus.Enriched;
|
||||
unchangedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
unchangedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
context.Books.AddRange(changedBook, unchangedBook);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
@@ -58,10 +58,10 @@ public class BookRepositoryTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.BookArtwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id);
|
||||
BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.Artwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id);
|
||||
Assert.NotNull(resetBook);
|
||||
Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus);
|
||||
Assert.Equal(ArtworkStatus.Pending, resetBook.BookArtwork.Single().Status);
|
||||
Assert.Equal(ArtworkStatus.Pending, resetBook.Artwork.Single().Status);
|
||||
BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == unchangedBook.Id);
|
||||
Assert.NotNull(keptBook);
|
||||
Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus);
|
||||
@@ -116,10 +116,10 @@ public class BookRepositoryTests
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
bookOfAnotherLibrary.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
context.Books.AddRange(book, bookOfAnotherLibrary);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
+7
-6
@@ -64,6 +64,7 @@ public class BooksFileSystemDiscoveryJobTests
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockDirectoryScanFingerprintRepository = Substitute.For<IDirectoryScanFingerprintRepository>();
|
||||
@@ -105,7 +106,7 @@ public class BooksFileSystemDiscoveryJobTests
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: [temporaryLibraryDirectory.Path],
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(libraryEntity));
|
||||
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Created));
|
||||
@@ -154,7 +155,7 @@ public class BooksFileSystemDiscoveryJobTests
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: [temporaryLibraryDirectory.Path],
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(libraryEntity));
|
||||
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>
|
||||
@@ -200,7 +201,7 @@ public class BooksFileSystemDiscoveryJobTests
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: [temporaryLibraryDirectory.Path],
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(libraryEntity));
|
||||
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to load the directory scan fingerprints"));
|
||||
@@ -228,7 +229,7 @@ public class BooksFileSystemDiscoveryJobTests
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: [temporaryLibraryDirectory.Path],
|
||||
shouldSkipUnchangedDirectoriesDuringScan: true);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(libraryEntity));
|
||||
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>()));
|
||||
@@ -259,7 +260,7 @@ public class BooksFileSystemDiscoveryJobTests
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: [temporaryLibraryDirectory.Path],
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(libraryEntity));
|
||||
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to insert the staging results"));
|
||||
@@ -289,7 +290,7 @@ public class BooksFileSystemDiscoveryJobTests
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: [temporaryLibraryDirectory.Path],
|
||||
shouldSkipUnchangedDirectoriesDuringScan: false);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(libraryEntity));
|
||||
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Created));
|
||||
|
||||
+1
@@ -67,6 +67,7 @@ public class BookReadingServiceTests : IDisposable
|
||||
_mockPluginManager.GetPlugins().Returns([_mockPlugin]);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
|
||||
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository);
|
||||
LibraryBookReaderConfigurationEntity enabledConfiguration = _configurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true);
|
||||
|
||||
-286
@@ -1,286 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.ValueObjects.Metadata;
|
||||
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 System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Common.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Custom JSON converter for the <see cref="Book"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookJsonConverter : JsonConverter<Book>
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads and converts JSON to a <see cref="Book"/> object.
|
||||
/// </summary>
|
||||
/// <param name="reader">The JSON reader.</param>
|
||||
/// <param name="typeToConvert">The type of the object to convert.</param>
|
||||
/// <param name="options">The serializer options.</param>
|
||||
/// <returns>The converted <see cref="Book"/> object.</returns>
|
||||
public override Book Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
using (JsonDocument doc = JsonDocument.ParseValue(ref reader))
|
||||
{
|
||||
JsonElement root = doc.RootElement;
|
||||
|
||||
Guid id = root.GetProperty("id").GetGuid();
|
||||
Guid libraryId = root.GetProperty("libraryId").GetGuid();
|
||||
string path = root.GetProperty("path").GetString()!;
|
||||
DateTime createdOnUtc = root.GetProperty("createdOnUtc").GetDateTime();
|
||||
WrittenContentMetadata metadata = DeserializeMetadata(root.GetProperty("metadata"));
|
||||
BookFormat? format = null;
|
||||
if (root.TryGetProperty("format", out JsonElement formatElement))
|
||||
{
|
||||
if (formatElement.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
string formatString = formatElement.GetString()!;
|
||||
if (Enum.TryParse(formatString, out BookFormat parsedFormat))
|
||||
format = parsedFormat;
|
||||
}
|
||||
}
|
||||
string? edition = root.GetProperty("edition").GetString();
|
||||
int volumeNumber = root.GetProperty("volumeNumber").GetInt32();
|
||||
BookSeries series = DeserializeBookSeries(root.GetProperty("series"));
|
||||
string? asin = root.GetProperty("asin").GetString();
|
||||
string? goodreadsId = root.GetProperty("goodreadsId").GetString();
|
||||
string? lccn = root.GetProperty("lccn").GetString();
|
||||
string? oclcNumber = root.GetProperty("oclcNumber").GetString();
|
||||
string? openLibraryId = root.GetProperty("openLibraryId").GetString();
|
||||
string? libraryThingId = root.GetProperty("libraryThingId").GetString();
|
||||
string? googleBooksId = root.GetProperty("googleBooksId").GetString();
|
||||
string? barnesAndNobleId = root.GetProperty("barnesAndNobleId").GetString();
|
||||
string? appleBooksId = root.GetProperty("appleBooksId").GetString();
|
||||
List<Isbn> isbns = DeserializeIsbns(root.GetProperty("isbNs"));
|
||||
List<MediaContributorId> contributorIds = DeserializeContributorIds(root.GetProperty("contributors"));
|
||||
List<BookRating> ratings = DeserializeRatings(root.GetProperty("ratings"));
|
||||
|
||||
Result<Book> createBookResult = Book.Create(
|
||||
BookId.Create(id),
|
||||
LibraryId.Create(libraryId),
|
||||
path,
|
||||
metadata,
|
||||
Optional<BookFormat>.FromNullable(format),
|
||||
Optional<string>.FromNullable(edition),
|
||||
volumeNumber,
|
||||
Optional<BookSeries>.FromNullable(series),
|
||||
Optional<string>.FromNullable(asin),
|
||||
Optional<string>.FromNullable(goodreadsId),
|
||||
Optional<string>.FromNullable(lccn),
|
||||
Optional<string>.FromNullable(oclcNumber),
|
||||
Optional<string>.FromNullable(openLibraryId),
|
||||
Optional<string>.FromNullable(libraryThingId),
|
||||
Optional<string>.FromNullable(googleBooksId),
|
||||
Optional<string>.FromNullable(barnesAndNobleId),
|
||||
Optional<string>.FromNullable(appleBooksId),
|
||||
createdOnUtc,
|
||||
default,
|
||||
isbns,
|
||||
contributorIds,
|
||||
ratings: ratings
|
||||
);
|
||||
if (createBookResult.IsFailure)
|
||||
throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}");
|
||||
return createBookResult.Value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a <see cref="Book"/> object to JSON. This method is not implemented.
|
||||
/// </summary>
|
||||
/// <param name="writer">The JSON writer.</param>
|
||||
/// <param name="value">The <see cref="Book"/> object to write.</param>
|
||||
/// <param name="options">The serializer options.</param>
|
||||
public override void Write(Utf8JsonWriter writer, Book value, JsonSerializerOptions options)
|
||||
{
|
||||
throw new NotImplementedException("Serialization is not implemented for Book class.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the metadata from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the metadata.</param>
|
||||
/// <returns>The deserialized <see cref="WrittenContentMetadata"/>.</returns>
|
||||
private static WrittenContentMetadata DeserializeMetadata(JsonElement element)
|
||||
{
|
||||
string? title = element.GetProperty("title").GetString();
|
||||
string? originalTitle = element.GetProperty("originalTitle").GetString();
|
||||
string? description = element.GetProperty("description").GetString();
|
||||
ReleaseInfo releaseInfo = DeserializeReleaseInfo(element.GetProperty("releaseInfo"));
|
||||
List<Genre> genres = DeserializeGenres(element.GetProperty("genres"));
|
||||
List<Tag> tags = DeserializeTags(element.GetProperty("tags"));
|
||||
LanguageInfo? language = DeserializeLanguageInfo(element.GetProperty("language"));
|
||||
LanguageInfo? originalLanguage = DeserializeLanguageInfo(element.GetProperty("originalLanguage"));
|
||||
string? publisher = element.GetProperty("publisher").GetString();
|
||||
int? pageCount = null;
|
||||
if (element.TryGetProperty("pageCount", out JsonElement pageCountElement))
|
||||
if (pageCountElement.ValueKind != JsonValueKind.Null)
|
||||
pageCount = pageCountElement.GetInt32();
|
||||
Result<WrittenContentMetadata> metadataResult = WrittenContentMetadata.Create(
|
||||
title!,
|
||||
Optional<string>.FromNullable(originalTitle),
|
||||
Optional<string>.FromNullable(description),
|
||||
releaseInfo,
|
||||
genres,
|
||||
tags,
|
||||
Optional<LanguageInfo>.FromNullable(language),
|
||||
Optional<LanguageInfo>.FromNullable(originalLanguage),
|
||||
Optional<string>.FromNullable(publisher),
|
||||
Optional<int>.FromNullable(pageCount)
|
||||
);
|
||||
|
||||
if (metadataResult.IsFailure)
|
||||
throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}");
|
||||
return metadataResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the release info from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the release info.</param>
|
||||
/// <returns>The deserialized <see cref="ReleaseInfo"/>.</returns>
|
||||
private static ReleaseInfo DeserializeReleaseInfo(JsonElement element)
|
||||
{
|
||||
DateOnly? originalReleaseDate = element.TryGetProperty("originalReleaseDate", out JsonElement ordElement) && ordElement.ValueKind != JsonValueKind.Null ?
|
||||
DateOnly.Parse(ordElement.GetString()!) : (DateOnly?)null;
|
||||
int? originalReleaseYear = element.TryGetProperty("originalReleaseYear", out JsonElement oryElement) && oryElement.ValueKind == JsonValueKind.Number
|
||||
? oryElement.GetInt32() : (int?)null;
|
||||
DateOnly? reReleaseDate = element.TryGetProperty("reReleaseDate", out JsonElement rrdElement) && rrdElement.ValueKind == JsonValueKind.String ?
|
||||
DateOnly.Parse(rrdElement.GetString()!) : (DateOnly?)null;
|
||||
int? reReleaseYear = element.TryGetProperty("reReleaseYear", out JsonElement rryElement) && rryElement.ValueKind == JsonValueKind.Number
|
||||
? rryElement.GetInt32() : (int?)null;
|
||||
string? releaseCountry = element.TryGetProperty("releaseCountry", out JsonElement rcElement) ?
|
||||
rcElement.GetString() : null;
|
||||
string? releaseVersion = element.TryGetProperty("releaseVersion", out JsonElement rvElement) ?
|
||||
rvElement.GetString() : null;
|
||||
|
||||
Optional<ReleaseCountry> releaseCountryValue = Optional<ReleaseCountry>.None();
|
||||
if (releaseCountry is not null && Enum.TryParse(releaseCountry, ignoreCase: true, out ReleaseCountry parsedReleaseCountry))
|
||||
releaseCountryValue = parsedReleaseCountry;
|
||||
Result<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
|
||||
Optional<DateOnly>.FromNullable(originalReleaseDate),
|
||||
Optional<int>.FromNullable(originalReleaseYear),
|
||||
Optional<DateOnly>.FromNullable(reReleaseDate),
|
||||
Optional<int>.FromNullable(reReleaseYear),
|
||||
releaseCountryValue,
|
||||
Optional<string>.FromNullable(releaseVersion)
|
||||
);
|
||||
|
||||
if (releaseInfoResult.IsFailure)
|
||||
throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}");
|
||||
return releaseInfoResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the genres from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the genres.</param>
|
||||
/// <returns>The deserialized list of <see cref="Genre"/>.</returns>
|
||||
private static List<Genre> DeserializeGenres(JsonElement element)
|
||||
{
|
||||
return [.. element.EnumerateArray().Select(g => Genre.Create(g.GetProperty("name").GetString()!).Value)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the tags from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the tags.</param>
|
||||
/// <returns>The deserialized list of <see cref="Tag"/>.</returns>
|
||||
private static List<Tag> DeserializeTags(JsonElement element)
|
||||
{
|
||||
return [.. element.EnumerateArray().Select(t => Tag.Create(t.GetProperty("name").GetString()!).Value)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the language info from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the language info.</param>
|
||||
/// <returns>The deserialized <see cref="LanguageInfo"/>.</returns>
|
||||
private static LanguageInfo? DeserializeLanguageInfo(JsonElement element)
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Null)
|
||||
{
|
||||
string? languageCode = element.GetProperty("languageCode").GetString();
|
||||
string? languageName = element.GetProperty("languageName").GetString();
|
||||
string? nativeName = element.TryGetProperty("nativeName", out JsonElement nnElement) ? nnElement.GetString() : null;
|
||||
|
||||
Result<LanguageInfo> languageInfoResult = LanguageInfo.Create(
|
||||
languageCode!,
|
||||
languageName!,
|
||||
Optional<string>.FromNullable(nativeName)
|
||||
);
|
||||
|
||||
if (languageInfoResult.IsFailure)
|
||||
throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}");
|
||||
return languageInfoResult.Value;
|
||||
}
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the book series from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the book series.</param>
|
||||
/// <returns>The deserialized <see cref="BookSeries"/>.</returns>
|
||||
private static BookSeries DeserializeBookSeries(JsonElement element)
|
||||
{
|
||||
// TODO: implement when book series are implemented
|
||||
return null!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the ISBNs from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the ISBNs.</param>
|
||||
/// <returns>The deserialized list of <see cref="Isbn"/>.</returns>
|
||||
private static List<Isbn> DeserializeIsbns(JsonElement element)
|
||||
{
|
||||
return [.. element.EnumerateArray()
|
||||
.Select(i => Isbn.Create(i.GetProperty("value").GetString()!,
|
||||
Enum.Parse<IsbnFormat>(i.GetProperty("format").GetString()!)).Value)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the contributor IDs from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the contributor IDs.</param>
|
||||
/// <returns>The deserialized list of <see cref="MediaContributorId"/>.</returns>
|
||||
private static List<MediaContributorId> DeserializeContributorIds(JsonElement element)
|
||||
{
|
||||
// TODO: implement when contributors are implemented
|
||||
return [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the ratings from JSON.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element containing the ratings.</param>
|
||||
/// <returns>The deserialized list of <see cref="BookRating"/>.</returns>
|
||||
private static List<BookRating> DeserializeRatings(JsonElement element)
|
||||
{
|
||||
return [.. element.EnumerateArray()
|
||||
.Select(r => BookRating.Create(
|
||||
r.GetProperty("value").GetInt32(),
|
||||
r.GetProperty("maxValue").GetInt32(),
|
||||
Optional<BookRatingSource>.FromNullable(Enum.Parse<BookRatingSource>(r.GetProperty("source").GetString()!)),
|
||||
Optional<int>.FromNullable(
|
||||
r.TryGetProperty("voteCount", out JsonElement voteCountElement) && voteCountElement.ValueKind != JsonValueKind.Null
|
||||
? voteCountElement.GetInt32()
|
||||
: (int?)null)
|
||||
).Value)];
|
||||
}
|
||||
}
|
||||
+93
-52
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
@@ -11,14 +11,13 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Converters;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -33,6 +32,7 @@ using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -48,12 +48,8 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
ReferenceHandler = ReferenceHandler.Preserve,
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = {
|
||||
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase),
|
||||
new BookJsonConverter()
|
||||
}
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly AddBookRequestFixture _requestBookFixture = new();
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
@@ -106,62 +102,62 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
|
||||
BookResponse? bookResponse = await response.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Assert.NotNull(bookResponse);
|
||||
|
||||
// metadata checks
|
||||
Assert.Equal(bookRequest.Metadata!.Title, bookResponse!.Metadata.Title);
|
||||
Assert.Equal(bookRequest.Metadata.OriginalTitle, bookResponse.Metadata.OriginalTitle.Value);
|
||||
Assert.Equal(bookRequest.Metadata.Description, bookResponse.Metadata.Description.Value);
|
||||
Assert.Equal(bookRequest.Metadata.Publisher, bookResponse.Metadata.Publisher.Value);
|
||||
Assert.Equal(bookRequest.Metadata.PageCount, bookResponse.Metadata.PageCount.Value);
|
||||
Assert.Equal(bookRequest.Metadata.OriginalTitle, bookResponse.Metadata.OriginalTitle);
|
||||
Assert.Equal(bookRequest.Metadata.Description, bookResponse.Metadata.Description);
|
||||
Assert.Equal(bookRequest.Metadata.Publisher, bookResponse.Metadata.Publisher);
|
||||
Assert.Equal(bookRequest.Metadata.PageCount, bookResponse.Metadata.PageCount);
|
||||
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate, bookResponse.Metadata.ReleaseInfo.OriginalReleaseDate.Value);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear, bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear.Value);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseDate, bookResponse.Metadata.ReleaseInfo.ReReleaseDate.Value);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseYear, bookResponse.Metadata.ReleaseInfo.ReReleaseYear.Value);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo!.ReleaseCountry, bookResponse.Metadata.ReleaseInfo.ReleaseCountry.Value);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseVersion, bookResponse.Metadata.ReleaseInfo.ReleaseVersion.Value);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate, bookResponse.Metadata.ReleaseInfo!.OriginalReleaseDate);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear, bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseDate, bookResponse.Metadata.ReleaseInfo.ReReleaseDate);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseYear, bookResponse.Metadata.ReleaseInfo.ReReleaseYear);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseCountry, bookResponse.Metadata.ReleaseInfo.ReleaseCountry);
|
||||
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseVersion, bookResponse.Metadata.ReleaseInfo.ReleaseVersion);
|
||||
|
||||
// language checks
|
||||
Assert.Equal(bookRequest.Metadata.Language!.LanguageCode, bookResponse.Metadata.Language.Value.LanguageCode);
|
||||
Assert.Equal(bookRequest.Metadata.Language.LanguageName, bookResponse.Metadata.Language.Value.LanguageName);
|
||||
Assert.Equal(bookRequest.Metadata.Language.NativeName, bookResponse.Metadata.Language.Value.NativeName.Value);
|
||||
Assert.Equal(bookRequest.Metadata.Language!.LanguageCode, bookResponse.Metadata.Language!.LanguageCode);
|
||||
Assert.Equal(bookRequest.Metadata.Language.LanguageName, bookResponse.Metadata.Language.LanguageName);
|
||||
Assert.Equal(bookRequest.Metadata.Language.NativeName, bookResponse.Metadata.Language.NativeName);
|
||||
|
||||
// original language checks
|
||||
Assert.Equal(bookRequest.Metadata.OriginalLanguage!.LanguageCode, bookResponse.Metadata.OriginalLanguage.Value.LanguageCode);
|
||||
Assert.Equal(bookRequest.Metadata.OriginalLanguage.LanguageName, bookResponse.Metadata.OriginalLanguage.Value.LanguageName);
|
||||
Assert.Equal(bookRequest.Metadata.OriginalLanguage.NativeName, bookResponse.Metadata.OriginalLanguage.Value.NativeName.Value);
|
||||
Assert.Equal(bookRequest.Metadata.OriginalLanguage!.LanguageCode, bookResponse.Metadata.OriginalLanguage!.LanguageCode);
|
||||
Assert.Equal(bookRequest.Metadata.OriginalLanguage.LanguageName, bookResponse.Metadata.OriginalLanguage.LanguageName);
|
||||
Assert.Equal(bookRequest.Metadata.OriginalLanguage.NativeName, bookResponse.Metadata.OriginalLanguage.NativeName);
|
||||
|
||||
// genres checks
|
||||
Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres.Count);
|
||||
Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres!.Count);
|
||||
Assert.Equal(
|
||||
bookRequest.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x),
|
||||
bookResponse.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x));
|
||||
|
||||
// tags checks
|
||||
Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags.Count);
|
||||
Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags!.Count);
|
||||
Assert.Equal(
|
||||
bookRequest.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x),
|
||||
bookResponse.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x));
|
||||
|
||||
// book specific properties
|
||||
Assert.Equal(bookRequest.Format, bookResponse.Format.Value);
|
||||
Assert.Equal(bookRequest.Edition, bookResponse.Edition.Value);
|
||||
Assert.Equal(bookRequest.VolumeNumber, bookResponse.VolumeNumber.Value);
|
||||
Assert.Equal(bookRequest.ASIN, bookResponse.ASIN.Value);
|
||||
Assert.Equal(bookRequest.GoodreadsId, bookResponse.GoodreadsId.Value);
|
||||
Assert.Equal(bookRequest.LCCN, bookResponse.LCCN.Value);
|
||||
Assert.Equal(bookRequest.OCLCNumber, bookResponse.OCLCNumber.Value);
|
||||
Assert.Equal(bookRequest.OpenLibraryId, bookResponse.OpenLibraryId.Value);
|
||||
Assert.Equal(bookRequest.LibraryThingId, bookResponse.LibraryThingId.Value);
|
||||
Assert.Equal(bookRequest.GoogleBooksId, bookResponse.GoogleBooksId.Value);
|
||||
Assert.Equal(bookRequest.BarnesAndNobleId, bookResponse.BarnesAndNobleId.Value);
|
||||
Assert.Equal(bookRequest.AppleBooksId, bookResponse.AppleBooksId.Value);
|
||||
Assert.Equal(bookRequest.Format, bookResponse.Format);
|
||||
Assert.Equal(bookRequest.Edition, bookResponse.Edition);
|
||||
Assert.Equal(bookRequest.VolumeNumber, bookResponse.VolumeNumber);
|
||||
Assert.Equal(bookRequest.ASIN, bookResponse.ASIN);
|
||||
Assert.Equal(bookRequest.GoodreadsId, bookResponse.GoodreadsId);
|
||||
Assert.Equal(bookRequest.LCCN, bookResponse.LCCN);
|
||||
Assert.Equal(bookRequest.OCLCNumber, bookResponse.OCLCNumber);
|
||||
Assert.Equal(bookRequest.OpenLibraryId, bookResponse.OpenLibraryId);
|
||||
Assert.Equal(bookRequest.LibraryThingId, bookResponse.LibraryThingId);
|
||||
Assert.Equal(bookRequest.GoogleBooksId, bookResponse.GoogleBooksId);
|
||||
Assert.Equal(bookRequest.BarnesAndNobleId, bookResponse.BarnesAndNobleId);
|
||||
Assert.Equal(bookRequest.AppleBooksId, bookResponse.AppleBooksId);
|
||||
|
||||
// ISBNs checks
|
||||
Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs.Count);
|
||||
Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs!.Count);
|
||||
var requestIsbnData = bookRequest.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList();
|
||||
var responseIsbnData = bookResponse.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList();
|
||||
Assert.Equal(requestIsbnData.Count, responseIsbnData.Count);
|
||||
@@ -172,9 +168,9 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
}
|
||||
|
||||
// ratings checks
|
||||
Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings.Count);
|
||||
Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings!.Count);
|
||||
var requestRatingData = bookRequest.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList();
|
||||
var responseRatingData = bookResponse.Ratings.Select(r => new { Source = r.Source.Value, r.Value, r.MaxValue, VoteCount = r.VoteCount.Value }).OrderBy(x => x.Source).ToList();
|
||||
var responseRatingData = bookResponse.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList();
|
||||
Assert.Equal(requestRatingData.Count, responseRatingData.Count);
|
||||
for (int i = 0; i < requestRatingData.Count; i++)
|
||||
{
|
||||
@@ -186,18 +182,18 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
|
||||
// series checks
|
||||
if (bookRequest.Series is not null)
|
||||
Assert.Equal(bookRequest.Series.Title, bookResponse.Series.Value.Metadata.Title);
|
||||
Assert.Equal(bookRequest.Series.Title, bookResponse.Series!.Title);
|
||||
else
|
||||
Assert.Null(bookResponse.Series.Value);
|
||||
Assert.Null(bookResponse.Series);
|
||||
|
||||
// check Location header
|
||||
Assert.NotNull(response.Headers.Location);
|
||||
string locationUri = response.Headers.Location!.ToString();
|
||||
Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id.Value}", locationUri);
|
||||
Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id}", locationUri);
|
||||
|
||||
// extract ID from Location header and compare
|
||||
string idFromHeader = locationUri.Split('/').Last();
|
||||
Assert.Equal(idFromHeader, bookResponse!.Id.ToString());
|
||||
Assert.Equal(idFromHeader, bookResponse.Id.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -1119,7 +1115,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.ContributorsListCannotBeNull.Description);
|
||||
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorsListCannotBeNull.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -1235,15 +1231,15 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
|
||||
BookResponse? bookResponse = await response.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
|
||||
Assert.NotNull(bookResponse);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<BookContributorEntity> links = [.. dbContext.Books
|
||||
.Include(book => book.BookContributors)
|
||||
.Single(book => book.Id == bookResponse!.Id.Value)
|
||||
.BookContributors];
|
||||
.Include(book => book.Contributors)
|
||||
.Single(book => book.Id == bookResponse!.Id)
|
||||
.Contributors];
|
||||
Assert.Equal(2, links.Count);
|
||||
Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId));
|
||||
Assert.Contains(links, link => link.Role == MediaContributorRole.Author);
|
||||
@@ -1754,6 +1750,51 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookRequest request = _requestBookFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []);
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", bookRequest, cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []);
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", bookRequest, cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Posts a request to add a book to the media library owned by the authenticated user of the current test.
|
||||
/// </summary>
|
||||
@@ -1821,7 +1862,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
{
|
||||
HttpResponseMessage response = await PostBookAsync(bookRequest);
|
||||
response.EnsureSuccessStatusCode();
|
||||
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
|
||||
BookResponse? bookResponse = await response.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Assert.NotNull(bookResponse);
|
||||
}
|
||||
|
||||
+70
-3
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
@@ -36,6 +37,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingAvailabilityEndpointTests"/> class.
|
||||
@@ -63,7 +65,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
|
||||
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/availability");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -79,7 +81,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
|
||||
public async Task GetReadingAvailability_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/availability");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/availability");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
@@ -91,6 +93,57 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingAvailability_WhenBookBelongsToAnotherUser_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingAvailability_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookId) = await SeedBookAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/availability");
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
|
||||
// reported as not found, without disclosing that the book exists in another library.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingAvailability_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/availability");
|
||||
|
||||
// Assert
|
||||
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
|
||||
// validation errors instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingAvailability_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
@@ -98,7 +151,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/availability");
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/availability");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
@@ -123,6 +176,20 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
|
||||
return (libraryId, bookId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user that is not the authenticated one and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
|
||||
+47
-9
@@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -52,7 +53,7 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
public async Task GetReadingManifest_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/manifest");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/manifest");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
@@ -66,13 +67,35 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid bookId = await SeedBookAsync(otherUserId);
|
||||
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/manifest");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingManifest_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookId) = await SeedBookAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/manifest");
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
|
||||
// reported as not found, without disclosing that the book exists in another library.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -80,10 +103,10 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid bookId = await SeedBookAsync(userId);
|
||||
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/manifest");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
|
||||
|
||||
// Assert
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
@@ -98,18 +121,33 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/manifest");
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/manifest");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingManifest_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/manifest");
|
||||
|
||||
// Assert
|
||||
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
|
||||
// validation errors instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/> and an EPUB book belonging to it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid userId)
|
||||
/// <returns>The Ids of the seeded library and book.</returns>
|
||||
private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
@@ -120,7 +158,7 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
dbContext.Libraries.Add(library);
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
return (libraryId, bookId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+47
-9
@@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -52,7 +53,7 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
public async Task GetReadingResource_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/cover");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/cover");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
@@ -66,13 +67,35 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid bookId = await SeedBookAsync(otherUserId);
|
||||
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/resources/cover");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/cover");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingResource_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookId) = await SeedBookAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/resources/cover");
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
|
||||
// reported as not found, without disclosing that the book exists in another library.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -80,10 +103,10 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid bookId = await SeedBookAsync(userId);
|
||||
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/resources/cover");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/cover");
|
||||
|
||||
// Assert
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
@@ -98,18 +121,33 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/cover");
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/cover");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingResource_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/resources/cover");
|
||||
|
||||
// Assert
|
||||
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
|
||||
// validation errors instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/> and an EPUB book belonging to it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid userId)
|
||||
/// <returns>The Ids of the seeded library and book.</returns>
|
||||
private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
@@ -120,7 +158,7 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
|
||||
dbContext.Libraries.Add(library);
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
return (libraryId, bookId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+47
-9
@@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -52,7 +53,7 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
|
||||
public async Task GetReadingSection_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/chapter-1");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/chapter-1");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
@@ -66,13 +67,35 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid bookId = await SeedBookAsync(otherUserId);
|
||||
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/sections/chapter-1");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/chapter-1");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingSection_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookId) = await SeedBookAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/sections/chapter-1");
|
||||
|
||||
// Assert
|
||||
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
|
||||
// reported as not found, without disclosing that the book exists in another library.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -80,10 +103,10 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid bookId = await SeedBookAsync(userId);
|
||||
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/sections/chapter-1");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/chapter-1");
|
||||
|
||||
// Assert
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
@@ -98,18 +121,33 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/chapter-1");
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/chapter-1");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingSection_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/sections/chapter-1");
|
||||
|
||||
// Assert
|
||||
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
|
||||
// validation errors instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/> and an EPUB book belonging to it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid userId)
|
||||
/// <returns>The Ids of the seeded library and book.</returns>
|
||||
private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
@@ -120,7 +158,7 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
|
||||
dbContext.Libraries.Add(library);
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
return (libraryId, bookId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+38
-3
@@ -1,4 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
@@ -35,6 +35,7 @@ using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -134,9 +135,9 @@ public class UpdateBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<BookContributorEntity> links = dbContext.Books
|
||||
.Include(book => book.BookContributors)
|
||||
.Include(book => book.Contributors)
|
||||
.Single(book => book.Id == bookId)
|
||||
.BookContributors
|
||||
.Contributors
|
||||
.ToList();
|
||||
Assert.Equal(2, links.Count);
|
||||
Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId));
|
||||
@@ -1792,6 +1793,40 @@ public class UpdateBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBook_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title");
|
||||
UpdateBookRequest request = _requestBookFixture.Create();
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request, cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBook_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title");
|
||||
UpdateBookRequest request = _requestBookFixture.Create();
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request, cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the book described by the provided request, seeding the media library, the book and the referenced media contributors.
|
||||
/// </summary>
|
||||
|
||||
+110
-13
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -63,19 +64,19 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookWithCoverAsync(userId, "/media/books/old-cover.jpg");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
string storedPath = JsonSerializer.Deserialize<string>(content)!;
|
||||
string storedPath = JsonSerializer.Deserialize<UpdateBookCoverResponse>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!.CoverPath;
|
||||
Assert.False(string.IsNullOrWhiteSpace(storedPath));
|
||||
Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
BookArtworkEntity coverArtwork = dbContext.Books
|
||||
.SelectMany(book => book.BookArtwork)
|
||||
.SelectMany(book => book.Artwork)
|
||||
.Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover);
|
||||
Assert.Equal(storedPath, coverArtwork.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
|
||||
@@ -86,21 +87,21 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId);
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
string storedPath = JsonSerializer.Deserialize<string>(content)!;
|
||||
string storedPath = JsonSerializer.Deserialize<UpdateBookCoverResponse>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!.CoverPath;
|
||||
Assert.False(string.IsNullOrWhiteSpace(storedPath));
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
BookArtworkEntity coverArtwork = dbContext.Books
|
||||
.SelectMany(book => book.BookArtwork)
|
||||
.SelectMany(book => book.Artwork)
|
||||
.Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover);
|
||||
Assert.Equal(storedPath, coverArtwork.FileName);
|
||||
}
|
||||
@@ -109,7 +110,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
public async Task UpdateBookCover_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
@@ -123,7 +124,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
public async Task UpdateBookCover_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/not-a-guid/cover", CreateCoverForm("cover.png"));
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/not-a-guid/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
@@ -138,10 +139,10 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId);
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
@@ -151,6 +152,25 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId);
|
||||
Guid otherLibraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{otherLibraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
@@ -158,12 +178,78 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithBookCoverCannotBeNull()
|
||||
{
|
||||
// Arrange
|
||||
MultipartFormDataContent form = [];
|
||||
form.Add(new StringContent("unrelated-field"), "unrelated-field");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/cover", form);
|
||||
|
||||
// Assert
|
||||
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("BookCoverCannotBeNull", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenUploadedFileIsNotAnImage_ShouldReturnUnprocessableEntityWithCoverFileMustBeAnImage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
|
||||
MultipartFormDataContent form = CreateCoverForm([1, 2, 3, 4, 5, 6, 7, 8], "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form);
|
||||
|
||||
// Assert
|
||||
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("CoverFileMustBeAnImage", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenUploadedFileIsTooLarge_ShouldReturnUnprocessableEntityWithFileTooLarge()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
|
||||
// The artwork size limit is 10 MiB, so the payload exceeds it by one byte.
|
||||
byte[] payload = new byte[(10 * 1024 * 1024) + 1];
|
||||
payload[0] = 137;
|
||||
payload[1] = 80;
|
||||
payload[2] = 78;
|
||||
payload[3] = 71;
|
||||
payload[4] = 13;
|
||||
payload[5] = 10;
|
||||
payload[6] = 26;
|
||||
payload[7] = 10;
|
||||
MultipartFormDataContent form = CreateCoverForm(payload, "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form);
|
||||
|
||||
// Assert
|
||||
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("FileTooLarge", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a multipart form carrying a minimal PNG-like payload.
|
||||
/// </summary>
|
||||
@@ -181,6 +267,17 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
payload[5] = 10;
|
||||
payload[6] = 26;
|
||||
payload[7] = 10;
|
||||
return CreateCoverForm(payload, fileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a multipart form carrying the provided payload as an uploaded file.
|
||||
/// </summary>
|
||||
/// <param name="payload">The bytes of the uploaded file.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
|
||||
private static MultipartFormDataContent CreateCoverForm(byte[] payload, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(payload);
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
@@ -203,7 +300,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false);
|
||||
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: bookId, artworkType: ArtworkType.Cover, fileName: existingCoverFileName, status: ArtworkStatus.Enriched);
|
||||
book.BookArtwork.Add(existingCover);
|
||||
book.Artwork.Add(existingCover);
|
||||
dbContext.Libraries.Add(library);
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+2
-2
@@ -38,11 +38,11 @@ public class EditBookViewEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
expectedBook.Metadata!.Title = "A book";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{expectedBook.Id}", expectedBook);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{expectedBook.LibraryId}/books/{expectedBook.Id}", expectedBook);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{expectedBook.Id}");
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{expectedBook.Id}?libraryId={expectedBook.LibraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
|
||||
+6
-5
@@ -38,11 +38,12 @@ public class GetBookDetailsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}", expectedBook);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}", expectedBook);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-book");
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-book?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
@@ -55,7 +56,7 @@ public class GetBookDetailsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(bookId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid());
|
||||
Assert.Contains($"books/{bookId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.Contains($"libraries/{libraryId}/books/{bookId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -66,10 +67,10 @@ public class GetBookDetailsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-book");
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-book?libraryId={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("books/", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -42,7 +42,7 @@ public class GetLibraryItemsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string searchTerm = "Harry";
|
||||
PaginatedBookLiteDto expectedResponse = _paginatedBookLiteDtoFixture.Create(data: [_bookLiteDtoFixture.Create(title: "Harry Potter")]);
|
||||
string expectedEndpoint = $"books/lite?libraryId={libraryId}¤tPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=True";
|
||||
string expectedEndpoint = $"libraries/{libraryId}/books/lite?currentPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=True";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedResponse);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={libraryId}¤tPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=true");
|
||||
|
||||
+7
-5
@@ -38,11 +38,12 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaWebFactor
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: bookId, isAvailable: true);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}/reading/availability", availability);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/availability", availability);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability");
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
@@ -62,10 +63,11 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaWebFactor
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}/reading/availability", _readingAvailabilityDtoFixture.Create(bookId: bookId));
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/availability", _readingAvailabilityDtoFixture.Create(bookId: bookId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability");
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
@@ -73,7 +75,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaWebFactor
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Contains($"books/{bookId}/reading/availability", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.Contains($"libraries/{libraryId}/books/{bookId}/reading/availability", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+6
-4
@@ -41,11 +41,12 @@ public class GetReadingManifestEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ReadingManifestDto manifest = _readingManifestDtoFixture.Create(title: "Test Book");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}/reading/manifest", manifest);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/manifest", manifest);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest");
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
@@ -65,12 +66,13 @@ public class GetReadingManifestEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterGetException($"books/{bookId}/reading/manifest", new ApiException(
|
||||
_apiFactory.ApiClientStub.RegisterGetException($"libraries/{libraryId}/books/{bookId}/reading/manifest", new ApiException(
|
||||
_problemDetailsDtoFixture.Create(detail: "NoReaderAvailable"),
|
||||
HttpStatusCode.NotFound));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest");
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest?libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
|
||||
+3
-2
@@ -38,12 +38,13 @@ public class GetReadingSectionEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string locationRef = "chapter-1";
|
||||
ReadingSectionDto section = _readingSectionDtoFixture.Create(locationRef: locationRef, contentHtml: "<p>Content</p>");
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}/reading/sections/{locationRef}", section);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/sections/{locationRef}", section);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-section?locationRef={locationRef}");
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-section?locationRef={locationRef}&libraryId={libraryId}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
|
||||
+35
-17
@@ -1,5 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
@@ -21,6 +26,8 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Writte
|
||||
public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly UpdateBookCoverDtoFixture _updateBookCoverDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
|
||||
@@ -36,11 +43,12 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string expectedPath = "/media/books/cover.png";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}/cover", expectedPath);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}/cover", _updateBookCoverDtoFixture.Create(coverPath: expectedPath));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, "cover.png");
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, libraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
@@ -53,7 +61,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedPath, json.RootElement.GetProperty("data").GetString());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover" && putRequest.Data as string == "cover.png");
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover" && putRequest.Data as string == "cover.png");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -61,11 +69,12 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid routeId = Guid.NewGuid();
|
||||
Guid formId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"books/{routeId}/cover", "/media/books/cover.png");
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{routeId}/cover", _updateBookCoverDtoFixture.Create(coverPath: "/media/books/cover.png"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(routeId, "cover.png");
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(routeId, libraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
MultipartFormDataContent form = (MultipartFormDataContent)uploadRequest.Content!;
|
||||
form.Add(new StringContent(formId.ToString()), "id");
|
||||
@@ -77,8 +86,8 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{routeId}/cover");
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{formId}/cover");
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{routeId}/cover");
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{formId}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -86,28 +95,32 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, "cover.png");
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, libraryId, "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover");
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenCalledWithoutUploadedFile_ShouldReturnBadRequest()
|
||||
public async Task UpdateBookCover_WhenCalledWithoutUploadedFile_ShouldForwardRequestAndReturnFailure()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "BookCoverCannotBeNull");
|
||||
_apiFactory.ApiClientStub.RegisterPutException($"libraries/{libraryId}/books/{bookId}/cover", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, $"libraries/{libraryId}/books/{bookId}/cover"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
MultipartFormDataContent noFileForm = [];
|
||||
noFileForm.Add(new StringContent("unrelated-field"));
|
||||
HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover")
|
||||
HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = noFileForm
|
||||
};
|
||||
@@ -116,10 +129,14 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover");
|
||||
// The web does not short-circuit the missing file; it forwards the request, and the API reports the missing cover
|
||||
// with the same BookCoverCannotBeNull validation error any other client receives.
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover" && putRequest.Data == null);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -128,7 +145,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), "cover.png");
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), Guid.NewGuid(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest);
|
||||
@@ -142,15 +159,16 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
/// Builds the multipart PUT request that uploads a cover to the book identified by <paramref name="bookId"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The route Id of the book whose cover is uploaded.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The configured upload request.</returns>
|
||||
private static HttpRequestMessage CreateUploadRequest(Guid bookId, string fileName)
|
||||
private static HttpRequestMessage CreateUploadRequest(Guid bookId, Guid libraryId, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover")
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddBook_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized()
|
||||
public async Task AddBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
|
||||
+59
-5
@@ -1,9 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
|
||||
@@ -14,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -26,14 +33,17 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaApiFactor
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetReadingAvailabilityEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingAvailability_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/availability");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/availability");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
@@ -52,15 +62,59 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaApiFactor
|
||||
[InlineData("'; DROP TABLE Books--")] // destructive injection
|
||||
public async Task GetReadingAvailability_WithSQLInjectionInBookId_ShouldNotLeakDatabaseDetails(string maliciousBookId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}/reading/availability");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Uri.EscapeDataString(maliciousBookId)}/reading/availability");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The {bookId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler.
|
||||
// The authenticated request reaches validation, where the unparseable route Id is reported as a clean validation error,
|
||||
// without executing the injected payload or leaking database details.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousBookId, content, StringComparison.Ordinal);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingAvailability_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
|
||||
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
|
||||
Guid bookId;
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
|
||||
}
|
||||
|
||||
HttpClient requesterClient = _apiFactory.CreateClient();
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, 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.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(requesterUsername);
|
||||
}
|
||||
}
|
||||
+55
-5
@@ -1,9 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
@@ -18,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingManifestEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -30,14 +33,17 @@ public class GetReadingManifestEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetReadingManifestEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingManifest_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/manifest");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/manifest");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
@@ -56,15 +62,59 @@ public class GetReadingManifestEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
[InlineData("'; DROP TABLE Books--")] // destructive injection
|
||||
public async Task GetReadingManifest_WithSQLInjectionInBookId_ShouldNotLeakDatabaseDetails(string maliciousBookId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}/reading/manifest");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Uri.EscapeDataString(maliciousBookId)}/reading/manifest");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// the {bookId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
|
||||
// The authenticated request reaches validation, where the unparseable route Id is reported as a clean validation error,
|
||||
// without executing the injected payload or leaking database details.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousBookId, content, StringComparison.Ordinal);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingManifest_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
|
||||
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
|
||||
Guid bookId;
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
|
||||
}
|
||||
|
||||
HttpClient requesterClient = _apiFactory.CreateClient();
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, 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.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(requesterUsername);
|
||||
}
|
||||
}
|
||||
+63
-5
@@ -1,9 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
@@ -18,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingResourceEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -30,14 +33,17 @@ public class GetReadingResourceEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetReadingResourceEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingResource_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/cover");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/resources/cover");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
@@ -56,15 +62,25 @@ public class GetReadingResourceEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
[InlineData("'; DROP TABLE Books--")] // destructive injection
|
||||
public async Task GetReadingResource_WithSQLInjectionInResourceKey_ShouldNotLeakDatabaseDetails(string maliciousResourceKey)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/{Uri.EscapeDataString(maliciousResourceKey)}");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/{Uri.EscapeDataString(maliciousResourceKey)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The authenticated request reaches the handler and the database, where the book does not exist, so the request fails
|
||||
// cleanly without executing the injected payload or leaking database details.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousResourceKey, content, StringComparison.Ordinal);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -72,13 +88,55 @@ public class GetReadingResourceEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
[InlineData("..%2F..%2Fetc%2Fpasswd")] // encoded directory traversal
|
||||
public async Task GetReadingResource_WithPathTraversalInResourceKey_ShouldNotExposeFilesystemPaths(string traversalPayload)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/{traversalPayload}");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/{traversalPayload}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("etc/passwd", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Stack Trace", content, StringComparison.Ordinal);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingResource_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
|
||||
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
|
||||
Guid bookId;
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
|
||||
}
|
||||
|
||||
HttpClient requesterClient = _apiFactory.CreateClient();
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/cover");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, 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.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(requesterUsername);
|
||||
}
|
||||
}
|
||||
+63
-5
@@ -1,9 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
@@ -18,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingSectionEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -30,14 +33,17 @@ public class GetReadingSectionEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetReadingSectionEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingSection_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/chapter-1");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/sections/chapter-1");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
@@ -56,15 +62,25 @@ public class GetReadingSectionEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
[InlineData("'; DROP TABLE Books--")] // destructive injection
|
||||
public async Task GetReadingSection_WithSQLInjectionInLocationRef_ShouldNotLeakDatabaseDetails(string maliciousLocationRef)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/{Uri.EscapeDataString(maliciousLocationRef)}");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/{Uri.EscapeDataString(maliciousLocationRef)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The authenticated request reaches the handler and the database, where the book does not exist, so the request fails
|
||||
// cleanly without executing the injected payload or leaking database details.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLocationRef, content, StringComparison.Ordinal);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -72,13 +88,55 @@ public class GetReadingSectionEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
[InlineData("..%2F..%2Fetc%2Fpasswd")] // encoded directory traversal
|
||||
public async Task GetReadingSection_WithPathTraversalInLocationRef_ShouldNotExposeFilesystemPaths(string traversalPayload)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/{traversalPayload}");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/{traversalPayload}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("etc/passwd", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Stack Trace", content, StringComparison.Ordinal);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetReadingSection_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
|
||||
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
|
||||
Guid bookId;
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
|
||||
}
|
||||
|
||||
HttpClient requesterClient = _apiFactory.CreateClient();
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/chapter-1");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, 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.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(requesterUsername);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -40,7 +40,7 @@ public class UpdateBookEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBook_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized()
|
||||
public async Task UpdateBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
|
||||
+53
-5
@@ -1,8 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
@@ -31,19 +36,62 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized()
|
||||
public async Task UpdateBookCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", form);
|
||||
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
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/{bookId}/cover", problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateBookCover_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
|
||||
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
|
||||
Guid bookId;
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
|
||||
}
|
||||
|
||||
HttpClient requesterClient = _apiFactory.CreateClient();
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
|
||||
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await requesterClient.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
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]
|
||||
@@ -57,7 +105,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}/cover", form);
|
||||
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Uri.EscapeDataString(maliciousBookId)}/cover", form);
|
||||
|
||||
// Assert
|
||||
// The unparseable route value becomes an empty book Id, which the command validator reports as a missing book Id.
|
||||
@@ -81,7 +129,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
MultipartFormDataContent form = CreateCoverForm("..\\..\\evil.jpg");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", form);
|
||||
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/cover", form);
|
||||
|
||||
// Assert
|
||||
// The book does not exist, so the handler returns a clean not found response before the uploaded file name is used.
|
||||
|
||||
+5
-4
@@ -44,7 +44,7 @@ public class GetBookDetailsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("books/", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -54,13 +54,14 @@ public class GetBookDetailsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string normalizedBookId = Guid.Empty.ToString();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"books/{normalizedBookId}", expectedBook);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{normalizedBookId}", expectedBook);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(maliciousBookId)}/api-get-book");
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(maliciousBookId)}/api-get-book?libraryId={libraryId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
@@ -73,6 +74,6 @@ public class GetBookDetailsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"books/{normalizedBookId}");
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/books/{normalizedBookId}");
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -41,7 +41,7 @@ public class GetLibraryItemsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("books/lite", StringComparison.Ordinal));
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -52,7 +52,7 @@ public class GetLibraryItemsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
string expectedEndpoint = $"libraries/{libraryId}/books/lite?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=False";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _paginatedBookLiteDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=false");
|
||||
|
||||
+12
-8
@@ -37,9 +37,10 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"books/{Guid.Empty}/cover", "/media/books/cover.png");
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{Guid.Empty}/cover", "/media/books/cover.png");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(maliciousBookId, "cover.png");
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(maliciousBookId, libraryId, "cover.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
@@ -51,7 +52,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{Guid.Empty}/cover");
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{Guid.Empty}/cover");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -59,9 +60,11 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"books/{Guid.NewGuid()}/cover", "/media/books/cover.png");
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}/cover", "/media/books/cover.png");
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid().ToString(), "..\\..\\evil.png");
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(bookId.ToString(), libraryId, "..\\..\\evil.png");
|
||||
uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
@@ -80,7 +83,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid().ToString(), "cover.png");
|
||||
HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid().ToString(), Guid.NewGuid(), "cover.png");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest);
|
||||
@@ -94,15 +97,16 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
/// Builds the multipart PUT request that uploads a cover to the book identified by <paramref name="bookId"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The route Id of the book whose cover is uploaded.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The configured upload request.</returns>
|
||||
private static HttpRequestMessage CreateUploadRequest(string bookId, string fileName)
|
||||
private static HttpRequestMessage CreateUploadRequest(string bookId, Guid libraryId, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "cover", fileName);
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-update-cover")
|
||||
return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-update-cover?libraryId={libraryId}")
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
|
||||
+3
-2
@@ -49,8 +49,9 @@ public class BookMappingTests
|
||||
Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageCode : null, result.OriginalLanguageCode);
|
||||
Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageName : null, result.OriginalLanguageName);
|
||||
Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.NativeName.Value : null, result.OriginalLanguageNativeName);
|
||||
Assert.Equal(book.Metadata.Tags.ToRepositoryEntities().OrderBy(tag => tag.Name), result.Tags.OrderBy(tag => tag.Name));
|
||||
Assert.Equal(book.Metadata.Genres.ToRepositoryEntities().OrderBy(genre => genre.Name), result.Genres.OrderBy(genre => genre.Name));
|
||||
// The repository entity stores tags and genres as sets, so duplicate names in the domain collection collapse into a single entry.
|
||||
Assert.Equal(book.Metadata.Tags.ToRepositoryEntities().Distinct().OrderBy(tag => tag.Name), result.Tags.OrderBy(tag => tag.Name));
|
||||
Assert.Equal(book.Metadata.Genres.ToRepositoryEntities().Distinct().OrderBy(genre => genre.Name), result.Genres.OrderBy(genre => genre.Name));
|
||||
Assert.Equal(book.Metadata.Publisher.HasValue ? book.Metadata.Publisher.Value : null, result.Publisher);
|
||||
Assert.Equal(book.Metadata.PageCount.HasValue ? book.Metadata.PageCount.Value : null, result.PageCount);
|
||||
Assert.Equal(book.Format.HasValue ? book.Format.Value : null, result.Format);
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
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="GetReadingAvailabilityRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingAvailabilityRequestMappingTests
|
||||
{
|
||||
private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetReadingAvailabilityQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(request.BookId, result.BookId);
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingManifestRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingManifestRequestMappingTests
|
||||
{
|
||||
private readonly GetReadingManifestRequestFixture _requestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestRequest request = _requestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetReadingManifestQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(request.BookId, result.BookId);
|
||||
}
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingResourceRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingResourceRequestMappingTests
|
||||
{
|
||||
private readonly GetReadingResourceRequestFixture _requestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceRequest request = _requestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetReadingResourceQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(request.BookId, result.BookId);
|
||||
Assert.Equal(request.ResourceKey, result.ResourceKey);
|
||||
}
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingSectionRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingSectionRequestMappingTests
|
||||
{
|
||||
private readonly GetReadingSectionRequestFixture _requestFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionRequest request = _requestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetReadingSectionQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(request.BookId, result.BookId);
|
||||
Assert.Equal(request.LocationRef, result.LocationRef);
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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="UpdateBookCoverCommandMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookCoverCommandMappingTests
|
||||
{
|
||||
private readonly UpdateBookCoverCommandFixture _commandFixture = new();
|
||||
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenBookHasNoCover_ShouldReturnANewEnrichedCoverArtwork()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(bookId: bookId.ToString());
|
||||
string storedCoverPath = "/media/books/cover.jpg";
|
||||
|
||||
// Act
|
||||
BookArtworkEntity cover = command.ToRepositoryEntity(null, bookId, storedCoverPath, userId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(bookId, cover.BookId);
|
||||
Assert.Equal(ArtworkType.Cover, cover.ArtworkType);
|
||||
Assert.Equal(0, cover.Ordinal);
|
||||
Assert.Equal(storedCoverPath, cover.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
|
||||
Assert.Equal(userId, cover.CreatedBy);
|
||||
Assert.NotEqual(default, cover.CreatedOnUtc);
|
||||
Assert.Null(cover.UpdatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToRepositoryEntity_WhenBookHasAnExistingCover_ShouldReplaceAndReturnTheStoredCover()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(bookId: bookId.ToString());
|
||||
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: bookId, artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg", status: ArtworkStatus.Pending);
|
||||
string storedCoverPath = "/media/books/cover.jpg";
|
||||
|
||||
// Act
|
||||
BookArtworkEntity cover = command.ToRepositoryEntity(existingCover, bookId, storedCoverPath, userId);
|
||||
|
||||
// Assert
|
||||
Assert.Same(existingCover, cover);
|
||||
Assert.Equal(storedCoverPath, cover.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, cover.Status);
|
||||
Assert.Equal(userId, cover.UpdatedBy);
|
||||
Assert.NotNull(cover.UpdatedOnUtc);
|
||||
Assert.NotNull(cover.LastUpdateUtc);
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="WrittenContentMetadataDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class WrittenContentMetadataDtoMappingTests
|
||||
{
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenMappingCompleteWrittenContentMetadataDto_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<WrittenContentMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(dto.Title, result.Value.Title);
|
||||
Assert.True(result.Value.OriginalTitle.HasValue);
|
||||
Assert.Equal(dto.OriginalTitle, result.Value.OriginalTitle.Value);
|
||||
Assert.True(result.Value.Description.HasValue);
|
||||
Assert.Equal(dto.Description, result.Value.Description.Value);
|
||||
Assert.Equal(dto.Genres!.Count, result.Value.Genres.Count);
|
||||
Assert.Equal(dto.Tags!.Count, result.Value.Tags.Count);
|
||||
Assert.True(result.Value.Language.HasValue);
|
||||
Assert.Equal(dto.Language!.LanguageCode!.ToLowerInvariant(), result.Value.Language.Value.LanguageCode);
|
||||
Assert.True(result.Value.OriginalLanguage.HasValue);
|
||||
Assert.Equal(dto.OriginalLanguage!.LanguageCode!.ToLowerInvariant(), result.Value.OriginalLanguage.Value.LanguageCode);
|
||||
Assert.True(result.Value.Publisher.HasValue);
|
||||
Assert.Equal(dto.Publisher, result.Value.Publisher.Value);
|
||||
Assert.True(result.Value.PageCount.HasValue);
|
||||
Assert.Equal(dto.PageCount!.Value, result.Value.PageCount.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenOptionalValuesAreMissing_ShouldMapWithoutOptionalValues()
|
||||
{
|
||||
// Arrange
|
||||
WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(
|
||||
includeOriginalTitle: false,
|
||||
includeDescription: false,
|
||||
includeLanguage: false,
|
||||
includeOriginalLanguage: false,
|
||||
includePublisher: false,
|
||||
includePageCount: false);
|
||||
|
||||
// Act
|
||||
Result<WrittenContentMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.OriginalTitle.HasValue);
|
||||
Assert.False(result.Value.Description.HasValue);
|
||||
Assert.False(result.Value.Language.HasValue);
|
||||
Assert.False(result.Value.OriginalLanguage.HasValue);
|
||||
Assert.False(result.Value.Publisher.HasValue);
|
||||
Assert.False(result.Value.PageCount.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenReleaseInfoCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(
|
||||
releaseInfo: _releaseInfoDtoFixture.Create(
|
||||
originalReleaseDate: new DateOnly(2025, 1, 1),
|
||||
originalReleaseYear: 2024));
|
||||
|
||||
// Act
|
||||
Result<WrittenContentMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenGenreCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")]);
|
||||
|
||||
// Act
|
||||
Result<WrittenContentMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToDomainEntity_WhenTagCreationFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")]);
|
||||
|
||||
// Act
|
||||
Result<WrittenContentMetadata> result = dto.ToDomainEntity();
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
}
|
||||
}
|
||||
+9
-9
@@ -1,10 +1,10 @@
|
||||
#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.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
@@ -321,9 +321,9 @@ public class AddBookCommandHandlerTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(insertedEntity);
|
||||
Assert.Equal(2, insertedEntity!.BookContributors.Count);
|
||||
Assert.Contains(insertedEntity.BookContributors, contributor => contributor.MediaContributorId == firstContributorId && contributor.Role == MediaContributorRole.Author);
|
||||
Assert.Contains(insertedEntity.BookContributors, contributor => contributor.MediaContributorId == secondContributorId && contributor.Role == MediaContributorRole.Illustrator);
|
||||
Assert.Equal(2, insertedEntity!.Contributors.Count);
|
||||
Assert.Contains(insertedEntity.Contributors, contributor => contributor.MediaContributorId == firstContributorId && contributor.Role == MediaContributorRole.Author);
|
||||
Assert.Contains(insertedEntity.Contributors, 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>());
|
||||
}
|
||||
@@ -355,10 +355,10 @@ public class AddBookCommandHandlerTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(insertedEntity);
|
||||
Assert.Equal(2, insertedEntity!.BookContributors.Count);
|
||||
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);
|
||||
Assert.Equal(2, insertedEntity!.Contributors.Count);
|
||||
Assert.All(insertedEntity.Contributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
|
||||
Assert.Contains(insertedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
|
||||
Assert.Contains(insertedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -1545,7 +1545,7 @@ public class AddBookCommandValidatorTests
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -1558,7 +1558,7 @@ public class AddBookCommandValidatorTests
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
|
||||
result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+40
-51
@@ -1,8 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
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;
|
||||
@@ -10,6 +12,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
@@ -42,6 +45,7 @@ public class UpdateBookCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMediaContributorRepository _mockMediaContributorRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
@@ -57,6 +61,7 @@ public class UpdateBookCommandHandlerTests
|
||||
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
|
||||
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
|
||||
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateBookCommandHandlerTests"/> class.
|
||||
@@ -64,10 +69,12 @@ public class UpdateBookCommandHandlerTests
|
||||
public UpdateBookCommandHandlerTests()
|
||||
{
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
@@ -82,6 +89,9 @@ public class UpdateBookCommandHandlerTests
|
||||
_mockValidator.Validate(Arg.Any<UpdateBookCommand>()).Returns([]);
|
||||
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
// Default stub: the library of the book exists.
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
|
||||
// Default stub: every referenced media contributor already exists.
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
@@ -268,10 +278,10 @@ public class UpdateBookCommandHandlerTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(updatedEntity);
|
||||
Assert.Equal(2, updatedEntity!.BookContributors.Count);
|
||||
Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
|
||||
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
|
||||
Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator);
|
||||
Assert.Equal(2, updatedEntity!.Contributors.Count);
|
||||
Assert.All(updatedEntity.Contributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId));
|
||||
Assert.Contains(updatedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author);
|
||||
Assert.Contains(updatedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -304,54 +314,12 @@ public class UpdateBookCommandHandlerTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(updatedEntity);
|
||||
Assert.Equal(2, updatedEntity!.BookContributors.Count);
|
||||
Assert.Equal(firstContributorId, updatedEntity.BookContributors[0].MediaContributorId);
|
||||
Assert.Equal(secondContributorId, updatedEntity.BookContributors[1].MediaContributorId);
|
||||
Assert.Equal(2, updatedEntity!.Contributors.Count);
|
||||
Assert.Equal(firstContributorId, updatedEntity.Contributors[0].MediaContributorId);
|
||||
Assert.Equal(secondContributorId, updatedEntity.Contributors[1].MediaContributorId);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenStoredBookHasEnrichmentAndCover_ShouldPreserveThemInTheResponse()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCommand command = _commandBookFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
existingBook.MetadataStatus = MetadataStatus.Enriched;
|
||||
existingBook.LastMetadataUpdateUtc = new DateTime(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc);
|
||||
existingBook.MetadataProvider = "TestProvider";
|
||||
existingBook.BookArtwork.Add(new BookArtworkEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookId = existingBook.Id,
|
||||
ArtworkType = ArtworkType.Cover,
|
||||
Ordinal = 0,
|
||||
FileName = "/media/covers/cover.jpg",
|
||||
Status = ArtworkStatus.Enriched,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedBy = null
|
||||
});
|
||||
BookEntity? updatedBook = null;
|
||||
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Result.From<BookEntity?>(callInfo.ArgAt<bool>(2) ? existingBook : updatedBook));
|
||||
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
updatedBook = callInfo.Arg<BookEntity>();
|
||||
return Result.Updated;
|
||||
});
|
||||
|
||||
// Act
|
||||
Result<BookResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(MetadataStatus.Enriched, result.Value.MetadataStatus);
|
||||
Assert.Equal(existingBook.LastMetadataUpdateUtc, result.Value.LastMetadataUpdateUtc);
|
||||
Assert.Equal(existingBook.MetadataProvider, result.Value.MetadataProvider);
|
||||
Assert.Equal("/media/covers/cover.jpg", result.Value.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalledWithInvalidIsbn_ShouldReturnFailureResult()
|
||||
{
|
||||
@@ -492,4 +460,25 @@ public class UpdateBookCommandHandlerTests
|
||||
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundErrorWithoutUpdating()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCommand command = _commandBookFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
_mockBookRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
_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(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1532,7 +1532,7 @@ public class UpdateBookCommandValidatorTests
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -1545,7 +1545,7 @@ public class UpdateBookCommandValidatorTests
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull);
|
||||
result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+142
-61
@@ -2,7 +2,7 @@
|
||||
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.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
@@ -12,6 +12,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
@@ -64,6 +65,7 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
|
||||
@@ -90,24 +92,24 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
|
||||
existingBook.BookArtwork = [];
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
existingBook.Artwork = [];
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
|
||||
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("/media/books/cover.jpg", result.Value);
|
||||
Assert.Single(existingBook.BookArtwork);
|
||||
Assert.Equal(ArtworkType.Cover, existingBook.BookArtwork[0].ArtworkType);
|
||||
Assert.Equal(result.Value, existingBook.BookArtwork[0].FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, existingBook.BookArtwork[0].Status);
|
||||
Assert.Equal("/media/books/cover.jpg", result.Value.CoverPath);
|
||||
Assert.Single(existingBook.Artwork);
|
||||
Assert.Equal(ArtworkType.Cover, existingBook.Artwork[0].ArtworkType);
|
||||
Assert.Equal(result.Value.CoverPath, existingBook.Artwork[0].FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, existingBook.Artwork[0].Status);
|
||||
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(
|
||||
existingBook.LibraryId,
|
||||
existingBook.Id,
|
||||
@@ -125,23 +127,23 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
|
||||
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: command.BookId, artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg");
|
||||
existingBook.BookArtwork = [existingCover];
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: Guid.Parse(command.BookId!), artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg");
|
||||
existingBook.Artwork = [existingCover];
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
|
||||
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("/media/books/cover.jpg", result.Value);
|
||||
Assert.Single(existingBook.BookArtwork);
|
||||
Assert.Equal(result.Value, existingCover.FileName);
|
||||
Assert.Equal("/media/books/cover.jpg", result.Value.CoverPath);
|
||||
Assert.Single(existingBook.Artwork);
|
||||
Assert.Equal(result.Value.CoverPath, existingCover.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, existingCover.Status);
|
||||
Assert.Equal(_userId, existingCover.UpdatedBy);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
@@ -152,24 +154,24 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "J.R.R. Tolkien");
|
||||
MediaContributorEntity illustrator = _mediaContributorEntityFixture.Create(displayName: "Alan Lee");
|
||||
existingBook.BookContributors =
|
||||
existingBook.Contributors =
|
||||
[
|
||||
_bookContributorEntityFixture.Create(bookId: command.BookId, mediaContributorId: author.Id, roleCategory: MediaContributorRoleCategory.Author),
|
||||
_bookContributorEntityFixture.Create(bookId: command.BookId, mediaContributorId: illustrator.Id, roleCategory: MediaContributorRoleCategory.Illustrator)
|
||||
_bookContributorEntityFixture.Create(bookId: Guid.Parse(command.BookId!), mediaContributorId: author.Id, role: MediaContributorRole.Author),
|
||||
_bookContributorEntityFixture.Create(bookId: Guid.Parse(command.BookId!), mediaContributorId: illustrator.Id, role: MediaContributorRole.Illustrator)
|
||||
];
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
|
||||
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MediaContributorEntity>>([author, illustrator]));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -185,37 +187,31 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAuthorResolutionFails_ShouldStoreArtworkWithEmptyAuthorName()
|
||||
public async Task HandleAsync_WhenAuthorResolutionFails_ShouldReturnFailureResultWithoutStoringArtwork()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
|
||||
existingBook.BookContributors =
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
existingBook.Contributors =
|
||||
[
|
||||
_bookContributorEntityFixture.Create(bookId: command.BookId, roleCategory: MediaContributorRoleCategory.Author)
|
||||
_bookContributorEntityFixture.Create(bookId: Guid.Parse(command.BookId!), role: MediaContributorRole.Author)
|
||||
];
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
|
||||
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockMediaContributorRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(
|
||||
existingBook.LibraryId,
|
||||
existingBook.Id,
|
||||
library.Title,
|
||||
string.Empty,
|
||||
existingBook.Title,
|
||||
Arg.Any<System.IO.Stream>(),
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -226,12 +222,12 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
_mockValidator.Validate(Arg.Any<UpdateBookCoverCommand>()).Returns([Errors.WrittenContent.BookCoverCannotBeNull]);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookCoverCannotBeNull, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -243,7 +239,7 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
@@ -256,16 +252,16 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -274,14 +270,14 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
|
||||
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
@@ -295,14 +291,14 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
|
||||
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
@@ -316,21 +312,106 @@ public class UpdateBookCoverCommandHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId);
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
|
||||
_mockBookRepository.GetByIdAsync(command.BookId, Arg.Any<CancellationToken>())
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.FileSystemManagement.FileTooLarge);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
// The stored book belongs to a different library than the one named by the route.
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.NewGuid());
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
|
||||
// Act
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReturningTheCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create();
|
||||
BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!));
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId);
|
||||
_mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(existingBook));
|
||||
_mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
|
||||
|
||||
// Act
|
||||
Result<UpdateBookCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
|
||||
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+92
-1
@@ -33,11 +33,50 @@ public class UpdateBookCoverCommandValidatorTests
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(libraryId: Guid.Empty.ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(libraryId: "not-a-guid");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(libraryId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.Empty);
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.Empty.ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
@@ -46,6 +85,32 @@ public class UpdateBookCoverCommandValidatorTests
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBookIdIsNotAGuid_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(bookId: "not-a-guid");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCoverIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
@@ -58,4 +123,30 @@ public class UpdateBookCoverCommandValidatorTests
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.BookCoverCannotBeNull);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCoverIsPresentAndFileNameIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(fileName: string.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCoverIsMissingAndFileNameIsEmpty_ShouldNotHaveFileNameValidationError()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverCommand command = _commandFixture.Create(fileName: string.Empty, includeCover: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
@@ -94,7 +94,7 @@ public class GetBookQueryHandlerTests
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
Guid contributorId = Guid.NewGuid();
|
||||
bookEntity.BookContributors =
|
||||
bookEntity.Contributors =
|
||||
[
|
||||
_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author)
|
||||
];
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
|
||||
+64
-18
@@ -1,7 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
@@ -57,6 +57,7 @@ public class GetReadingAvailabilityQueryHandlerTests
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
@@ -79,12 +80,14 @@ public class GetReadingAvailabilityQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
|
||||
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: book.Id, libraryId: book.LibraryId, isAvailable: true);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
@@ -100,12 +103,14 @@ public class GetReadingAvailabilityQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
|
||||
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: book.Id, libraryId: book.LibraryId, isAvailable: false, errorCode: nameof(Errors.Reading.ReaderDisabled));
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
@@ -122,7 +127,8 @@ public class GetReadingAvailabilityQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -133,14 +139,35 @@ public class GetReadingAvailabilityQueryHandlerTests
|
||||
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid());
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
|
||||
// Act
|
||||
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -156,8 +183,10 @@ public class GetReadingAvailabilityQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -167,7 +196,7 @@ public class GetReadingAvailabilityQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -185,7 +214,24 @@ public class GetReadingAvailabilityQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -193,16 +239,16 @@ public class GetReadingAvailabilityQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetReadingAvailabilityQuery>()).Returns([Errors.Reading.BookIdCannotBeEmpty]);
|
||||
_mockValidator.Validate(Arg.Any<GetReadingAvailabilityQuery>()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<ReadingAvailabilityResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Reading.BookIdCannotBeEmpty, result.FirstError);
|
||||
Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+37
-16
@@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
@@ -21,20 +20,7 @@ public class GetReadingAvailabilityQueryValidatorTests
|
||||
private readonly GetReadingAvailabilityQueryFixture _getReadingAvailabilityQueryFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(bookId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
|
||||
public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create();
|
||||
@@ -43,6 +29,41 @@ public class GetReadingAvailabilityQueryValidatorTests
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData("not-a-library-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create() with { LibraryId = libraryId };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData("not-a-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create() with { BookId = bookId };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+64
-18
@@ -2,7 +2,7 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
@@ -63,6 +63,7 @@ public class GetReadingManifestQueryHandlerTests
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
|
||||
@@ -87,12 +88,14 @@ public class GetReadingManifestQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
|
||||
ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create();
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages: false, cancellationToken).Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
@@ -108,14 +111,16 @@ public class GetReadingManifestQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true);
|
||||
ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create();
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages: true, cancellationToken).Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
@@ -131,7 +136,8 @@ public class GetReadingManifestQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -142,14 +148,35 @@ public class GetReadingManifestQueryHandlerTests
|
||||
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid());
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
|
||||
// Act
|
||||
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -165,8 +192,10 @@ public class GetReadingManifestQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -176,7 +205,7 @@ public class GetReadingManifestQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -194,7 +223,24 @@ public class GetReadingManifestQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -202,16 +248,16 @@ public class GetReadingManifestQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetReadingManifestQuery>()).Returns([Errors.Reading.BookIdCannotBeEmpty]);
|
||||
_mockValidator.Validate(Arg.Any<GetReadingManifestQuery>()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<ReadingManifestResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Reading.BookIdCannotBeEmpty, result.FirstError);
|
||||
Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+37
-16
@@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
@@ -21,20 +20,7 @@ public class GetReadingManifestQueryValidatorTests
|
||||
private readonly GetReadingManifestQueryFixture _getReadingManifestQueryFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(bookId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
|
||||
public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create();
|
||||
@@ -43,6 +29,41 @@ public class GetReadingManifestQueryValidatorTests
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData("not-a-library-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create() with { LibraryId = libraryId };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData("not-a-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create() with { BookId = bookId };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+61
-15
@@ -2,7 +2,7 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
@@ -63,6 +63,7 @@ public class GetReadingResourceQueryHandlerTests
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
|
||||
@@ -87,12 +88,14 @@ public class GetReadingResourceQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
|
||||
ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create();
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages: false, cancellationToken).Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
@@ -108,14 +111,16 @@ public class GetReadingResourceQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true);
|
||||
ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create();
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages: true, cancellationToken).Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
@@ -131,7 +136,8 @@ public class GetReadingResourceQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -142,14 +148,35 @@ public class GetReadingResourceQueryHandlerTests
|
||||
await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid());
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
|
||||
// Act
|
||||
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -165,8 +192,10 @@ public class GetReadingResourceQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -192,7 +221,24 @@ public class GetReadingResourceQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create();
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<ReadingResourceDataDto> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -208,7 +254,7 @@ public class GetReadingResourceQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Reading.ResourceKeyCannotBeEmpty, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+51
-28
@@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
@@ -20,32 +19,6 @@ public class GetReadingResourceQueryValidatorTests
|
||||
private readonly GetReadingResourceQueryValidator _validator = new();
|
||||
private readonly GetReadingResourceQueryFixture _getReadingResourceQueryFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(bookId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenResourceKeyIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(resourceKey: string.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
@@ -56,7 +29,57 @@ public class GetReadingResourceQueryValidatorTests
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData("not-a-library-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create() with { LibraryId = libraryId };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData("not-a-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create() with { BookId = bookId };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
public void Validate_WhenResourceKeyIsEmpty_ShouldHaveValidationError(string? resourceKey)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create() with { ResourceKey = resourceKey };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+71
-21
@@ -2,7 +2,7 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
@@ -63,6 +63,7 @@ public class GetReadingSectionQueryHandlerTests
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
|
||||
@@ -87,12 +88,14 @@ public class GetReadingSectionQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
|
||||
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages: false, shouldPreserveStyles: true, cancellationToken).Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
@@ -108,14 +111,16 @@ public class GetReadingSectionQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true);
|
||||
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages: true, shouldPreserveStyles: true, cancellationToken).Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
@@ -133,14 +138,16 @@ public class GetReadingSectionQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
|
||||
UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: shouldPreserveBookStyles);
|
||||
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From<UserSettingsEntity?>(settings));
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookReadingService.GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>()).Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
@@ -157,12 +164,14 @@ public class GetReadingSectionQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook);
|
||||
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookReadingService.GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>()).Returns(expectedResponse);
|
||||
|
||||
// Act
|
||||
@@ -180,7 +189,8 @@ public class GetReadingSectionQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -191,14 +201,35 @@ public class GetReadingSectionQueryHandlerTests
|
||||
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid());
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
|
||||
// Act
|
||||
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -214,8 +245,10 @@ public class GetReadingSectionQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(id: query.BookId);
|
||||
_mockBookRepository.GetByIdAsync(query.BookId, Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
Guid libraryId = Guid.Parse(query.LibraryId!);
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From<BookEntity?>(book));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
@@ -241,7 +274,24 @@ public class GetReadingSectionQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create();
|
||||
Guid bookId = Guid.Parse(query.BookId!);
|
||||
_mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Act
|
||||
Result<ReadingSectionDto> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -257,7 +307,7 @@ public class GetReadingSectionQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Reading.LocationRefCannotBeEmpty, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<LibraryType>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+51
-28
@@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
@@ -20,32 +19,6 @@ public class GetReadingSectionQueryValidatorTests
|
||||
private readonly GetReadingSectionQueryValidator _validator = new();
|
||||
private readonly GetReadingSectionQueryFixture _getReadingSectionQueryFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(bookId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLocationRefIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(locationRef: string.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
@@ -56,7 +29,57 @@ public class GetReadingSectionQueryValidatorTests
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
result.ShouldNotHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData("not-a-library-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create() with { LibraryId = libraryId };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
[InlineData("not-a-guid")] // non-Guid route value
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
|
||||
public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create() with { BookId = bookId };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // missing route value
|
||||
[InlineData("")] // empty route value
|
||||
public void Validate_WhenLocationRefIsEmpty_ShouldHaveValidationError(string? locationRef)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create() with { LocationRef = locationRef };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+1
@@ -45,6 +45,7 @@ public class SetLibraryBookReaderEnabledCommandHandlerTests
|
||||
public SetLibraryBookReaderEnabledCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockLibraryBookReaderConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
|
||||
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
|
||||
+12
-8
@@ -2,6 +2,8 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
@@ -49,6 +51,7 @@ public class GetLibraryBookReadersQueryHandlerTests
|
||||
public GetLibraryBookReadersQueryHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockLibraryBookReaderConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
|
||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository);
|
||||
@@ -104,7 +107,8 @@ public class GetLibraryBookReadersQueryHandlerTests
|
||||
_pluginEntityFixture.Create(enabledPluginId, "A Reader"),
|
||||
_pluginEntityFixture.Create(disabledPluginId, "B Reader")
|
||||
];
|
||||
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(plugins);
|
||||
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new PaginatedResultDto<PluginEntity> { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 }));
|
||||
Dictionary<Guid, IReadOnlyList<string>> supportedExtensions = new()
|
||||
{
|
||||
[enabledPluginId] = [".epub"],
|
||||
@@ -138,8 +142,8 @@ public class GetLibraryBookReadersQueryHandlerTests
|
||||
];
|
||||
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>(configurations));
|
||||
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<PluginEntity>>([_pluginEntityFixture.Create()]));
|
||||
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new PaginatedResultDto<PluginEntity> { Data = [_pluginEntityFixture.Create()], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 }));
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -159,8 +163,8 @@ public class GetLibraryBookReadersQueryHandlerTests
|
||||
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
|
||||
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
|
||||
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<PluginEntity>>([]));
|
||||
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new PaginatedResultDto<PluginEntity> { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 }));
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
@@ -184,7 +188,7 @@ public class GetLibraryBookReadersQueryHandlerTests
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
|
||||
await _mockPluginRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -194,7 +198,7 @@ public class GetLibraryBookReadersQueryHandlerTests
|
||||
GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create();
|
||||
_mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
|
||||
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure(description: "Failed to get plugins"));
|
||||
|
||||
// Act
|
||||
@@ -219,7 +223,7 @@ public class GetLibraryBookReadersQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
|
||||
await _mockPluginRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ public class BookMetadataDtoTests
|
||||
"1234567890",
|
||||
"id12345",
|
||||
[new IsbnDto("978-0-306-40615-7", IsbnFormat.Isbn13)],
|
||||
[new MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), new MediaContributorRoleDto("Author", MediaContributorRoleCategory.Author))],
|
||||
[new MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), MediaContributorRole.Author)],
|
||||
[new BookRatingDto(4.5m, 5m, BookRatingSource.Goodreads, 1000)],
|
||||
"https://example.com/dune.jpg"
|
||||
);
|
||||
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingAvailabilityRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingAvailabilityRequestTests
|
||||
{
|
||||
private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new();
|
||||
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalled_ShouldReturnValidGetReadingAvailabilityRequest()
|
||||
{
|
||||
// Act
|
||||
GetReadingAvailabilityRequest sut = _getReadingAvailabilityRequestFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut);
|
||||
Assert.NotEqual(Guid.Empty, sut.BookId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_WhenSerializingGetReadingAvailabilityRequest_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityRequest expected = _getReadingAvailabilityRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
GetReadingAvailabilityRequest? actual = JsonSerializer.Deserialize<GetReadingAvailabilityRequest>(json, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(actual);
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingManifestRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingManifestRequestTests
|
||||
{
|
||||
private readonly GetReadingManifestRequestFixture _getReadingManifestRequestFixture = new();
|
||||
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalled_ShouldReturnValidGetReadingManifestRequest()
|
||||
{
|
||||
// Act
|
||||
GetReadingManifestRequest sut = _getReadingManifestRequestFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut);
|
||||
Assert.NotEqual(Guid.Empty, sut.BookId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_WhenSerializingGetReadingManifestRequest_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestRequest expected = _getReadingManifestRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
GetReadingManifestRequest? actual = JsonSerializer.Deserialize<GetReadingManifestRequest>(json, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(actual);
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingResourceRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingResourceRequestTests
|
||||
{
|
||||
private readonly GetReadingResourceRequestFixture _getReadingResourceRequestFixture = new();
|
||||
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalled_ShouldReturnValidGetReadingResourceRequest()
|
||||
{
|
||||
// Act
|
||||
GetReadingResourceRequest sut = _getReadingResourceRequestFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut);
|
||||
Assert.NotEqual(Guid.Empty, sut.BookId);
|
||||
Assert.False(string.IsNullOrWhiteSpace(sut.ResourceKey));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_WhenSerializingGetReadingResourceRequest_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceRequest expected = _getReadingResourceRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
GetReadingResourceRequest? actual = JsonSerializer.Deserialize<GetReadingResourceRequest>(json, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(actual);
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetReadingSectionRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetReadingSectionRequestTests
|
||||
{
|
||||
private readonly GetReadingSectionRequestFixture _getReadingSectionRequestFixture = new();
|
||||
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalled_ShouldReturnValidGetReadingSectionRequest()
|
||||
{
|
||||
// Act
|
||||
GetReadingSectionRequest sut = _getReadingSectionRequestFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut);
|
||||
Assert.NotEqual(Guid.Empty, sut.BookId);
|
||||
Assert.False(string.IsNullOrWhiteSpace(sut.LocationRef));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_WhenSerializingGetReadingSectionRequest_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionRequest expected = _getReadingSectionRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
GetReadingSectionRequest? actual = JsonSerializer.Deserialize<GetReadingSectionRequest>(json, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(actual);
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="UpdateBookCoverResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookCoverResponseTests
|
||||
{
|
||||
private readonly UpdateBookCoverResponseFixture _updateBookCoverResponseFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_WhenSerializingUpdateBookCoverResponse_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverResponse expected = _updateBookCoverResponseFixture.Create();
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
UpdateBookCoverResponse? actual = JsonSerializer.Deserialize<UpdateBookCoverResponse>(json, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(actual);
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deconstruct_WhenCalled_ShouldReturnAllProperties()
|
||||
{
|
||||
// Arrange
|
||||
UpdateBookCoverResponse sut = _updateBookCoverResponseFixture.Create();
|
||||
|
||||
// Act
|
||||
sut.Deconstruct(out string coverPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(sut.CoverPath, coverPath);
|
||||
}
|
||||
}
|
||||
+47
-20
@@ -11,7 +11,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Filtering;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.DataAccess.Core.Repositories.Books;
|
||||
using Lumina.DataAccess.Core.Repositories.BookLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -29,7 +29,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books;
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookRepository"/> class.
|
||||
@@ -441,7 +441,7 @@ public class BookRepositoryTests
|
||||
.Include(book => book.Genres)
|
||||
.Include(book => book.ISBNs)
|
||||
.Include(book => book.Ratings)
|
||||
.Include(book => book.BookContributors)
|
||||
.Include(book => book.Contributors)
|
||||
.FirstOrDefaultAsync(book => book.Id == storedBook.Id);
|
||||
Assert.NotNull(retrievedBook);
|
||||
Assert.Equal("Updated Title", retrievedBook!.Title);
|
||||
@@ -455,6 +455,33 @@ public class BookRepositoryTests
|
||||
Assert.Equal(storedCreatedBy, retrievedBook.CreatedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenStoredBookHasArtwork_ShouldPreserveTheStoredArtwork()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity storedBook = _bookEntityFixture.Create();
|
||||
storedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: storedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched, fileName: "cover.jpg")];
|
||||
_mockContext.Books.Add(storedBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
BookEntity data = _bookEntityFixture.Create(id: storedBook.Id);
|
||||
data.Title = "Updated Title";
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookEntity? retrievedBook = await _mockContext.Books
|
||||
.Include(book => book.Artwork)
|
||||
.FirstOrDefaultAsync(book => book.Id == storedBook.Id);
|
||||
Assert.NotNull(retrievedBook);
|
||||
BookArtworkEntity retrievedArtwork = Assert.Single(retrievedBook!.Artwork);
|
||||
Assert.Equal("cover.jpg", retrievedArtwork.FileName);
|
||||
Assert.Equal(ArtworkStatus.Enriched, retrievedArtwork.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_WhenDataContainsExistingTagAndGenreNames_ShouldReuseTheStoredTagAndGenreEntities()
|
||||
{
|
||||
@@ -498,14 +525,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, role: MediaContributorRole.Author)];
|
||||
storedBook.Contributors = [_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(), role: MediaContributorRole.Illustrator)];
|
||||
data.Contributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Illustrator)];
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
|
||||
@@ -516,12 +543,12 @@ public class BookRepositoryTests
|
||||
BookEntity? retrievedBook = await _mockContext.Books
|
||||
.Include(book => book.ISBNs)
|
||||
.Include(book => book.Ratings)
|
||||
.Include(book => book.BookContributors)
|
||||
.Include(book => book.Contributors)
|
||||
.FirstOrDefaultAsync(book => book.Id == storedBook.Id);
|
||||
Assert.NotNull(retrievedBook);
|
||||
IsbnEntity retrievedIsbn = Assert.Single(retrievedBook!.ISBNs);
|
||||
BookRatingEntity retrievedRating = Assert.Single(retrievedBook.Ratings);
|
||||
BookContributorEntity retrievedContributor = Assert.Single(retrievedBook.BookContributors);
|
||||
BookContributorEntity retrievedContributor = Assert.Single(retrievedBook.Contributors);
|
||||
Assert.Equal("9780261102693", retrievedIsbn.Value);
|
||||
Assert.Equal(3.5M, retrievedRating.Value);
|
||||
Assert.Equal(MediaContributorRole.Illustrator, retrievedContributor.Role);
|
||||
@@ -724,18 +751,18 @@ public class BookRepositoryTests
|
||||
BookEntity bookWithoutCover = _bookEntityFixture.Create();
|
||||
bookWithoutCover.LibraryId = libraryId;
|
||||
bookWithoutCover.Path = "/books/a.epub";
|
||||
bookWithoutCover.BookArtwork = [];
|
||||
bookWithoutCover.Artwork = [];
|
||||
BookEntity bookWithEnrichedCover = _bookEntityFixture.Create();
|
||||
bookWithEnrichedCover.LibraryId = libraryId;
|
||||
bookWithEnrichedCover.Path = "/books/b.epub";
|
||||
bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
bookWithEnrichedCover.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
BookEntity bookWithFailedCover = _bookEntityFixture.Create();
|
||||
bookWithFailedCover.LibraryId = libraryId;
|
||||
bookWithFailedCover.Path = "/books/c.epub";
|
||||
bookWithFailedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithFailedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Failed)];
|
||||
bookWithFailedCover.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookWithFailedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Failed)];
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.BookArtwork = [];
|
||||
bookOfAnotherLibrary.Artwork = [];
|
||||
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
@@ -756,13 +783,13 @@ public class BookRepositoryTests
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity bookWithoutCover = _bookEntityFixture.Create();
|
||||
bookWithoutCover.LibraryId = libraryId;
|
||||
bookWithoutCover.BookArtwork = [];
|
||||
bookWithoutCover.Artwork = [];
|
||||
BookEntity bookWithEnrichedCover = _bookEntityFixture.Create();
|
||||
bookWithEnrichedCover.LibraryId = libraryId;
|
||||
bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
bookWithEnrichedCover.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.BookArtwork = [];
|
||||
bookOfAnotherLibrary.Artwork = [];
|
||||
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
@@ -813,7 +840,7 @@ public class BookRepositoryTests
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAsync(book.Id, CancellationToken.None);
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(book.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -827,7 +854,7 @@ public class BookRepositoryTests
|
||||
public async Task DeleteAsync_WhenBookDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
Result<Deleted> result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
@@ -869,7 +896,7 @@ public class BookRepositoryTests
|
||||
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)];
|
||||
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
@@ -882,7 +909,7 @@ public class BookRepositoryTests
|
||||
Assert.Equal(2, retrievedBook.Tags.Count);
|
||||
Assert.Equal(2, retrievedBook.Genres.Count);
|
||||
Assert.Equal(2, retrievedBook.ISBNs.Count);
|
||||
Assert.Single(retrievedBook.BookArtwork);
|
||||
Assert.Single(retrievedBook.Artwork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -1320,7 +1347,7 @@ public class BookRepositoryTests
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, fileName: "cover.jpg")];
|
||||
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, fileName: "cover.jpg")];
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
@@ -1342,7 +1369,7 @@ public class BookRepositoryTests
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
book.BookArtwork = [];
|
||||
book.Artwork = [];
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary.Specifications;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookAlphaFilterSpecification"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookAlphaFilterSpecificationTests : IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection;
|
||||
private readonly LuminaDbContext _context;
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookAlphaFilterSpecificationTests"/> class.
|
||||
/// </summary>
|
||||
public BookAlphaFilterSpecificationTests()
|
||||
{
|
||||
// the specification translates to the SQLite glob() function, so it can only be exercised against a real SQLite database
|
||||
_connection = new SqliteConnection("Data Source=:memory:");
|
||||
_connection.Open();
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connection).Options);
|
||||
_context.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenAlphaKeyIsNull_ShouldMatchEveryBook()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> books = SeedBooks(("Alpha", null), ("Beta", null), ("1984", null));
|
||||
BookAlphaFilterSpecification specification = new(null, false);
|
||||
|
||||
// Act
|
||||
List<BookEntity> result = [.. _context.Books.Where(specification.ToExpression())];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(books.Count, result.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenAlphaKeyIsALowercaseLetter_ShouldMatchOnlyBooksWhoseTitleStartsWithIt()
|
||||
{
|
||||
// Arrange
|
||||
SeedBooks(("Fellowship", null), ("Hobbit", null), ("The Two Towers", null));
|
||||
BookAlphaFilterSpecification specification = new("f", false);
|
||||
|
||||
// Act
|
||||
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(["Fellowship"], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenAlphaKeyIsAnUppercaseLetter_ShouldMatchBooksWhoseTitleStartsWithItsLowercase()
|
||||
{
|
||||
// Arrange
|
||||
SeedBooks(("Fellowship", null), ("Hobbit", null));
|
||||
BookAlphaFilterSpecification specification = new("F", false);
|
||||
|
||||
// Act
|
||||
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(["Fellowship"], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenNoTitleStartsWithTheAlphaKey_ShouldNotMatchAnyBook()
|
||||
{
|
||||
// Arrange
|
||||
SeedBooks(("Fellowship", null), ("Hobbit", null));
|
||||
BookAlphaFilterSpecification specification = new("z", false);
|
||||
|
||||
// Act
|
||||
List<BookEntity> result = [.. _context.Books.Where(specification.ToExpression())];
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenAlphaKeyIsTheNumberKey_ShouldMatchOnlyBooksWhoseTitleStartsWithADigit()
|
||||
{
|
||||
// Arrange
|
||||
SeedBooks(("1984", null), ("Alpha", null), ("Beta", null));
|
||||
BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false);
|
||||
|
||||
// Act
|
||||
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(["1984"], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenAlphaKeyIsTheSymbolKey_ShouldMatchOnlyBooksWhoseTitleStartsWithASymbol()
|
||||
{
|
||||
// Arrange
|
||||
SeedBooks(("!Important", null), ("1984", null), ("Alpha", null));
|
||||
BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false);
|
||||
|
||||
// Act
|
||||
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(["!Important"], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenTitleIsEmpty_ShouldMatchOnTheOriginalTitle()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create(title: string.Empty, originalTitle: "Rendezvous", includeMetadata: false);
|
||||
_context.Books.Add(book);
|
||||
_context.SaveChanges();
|
||||
BookAlphaFilterSpecification specification = new("r", false);
|
||||
|
||||
// Act
|
||||
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(entity => entity.OriginalTitle!)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(["Rendezvous"], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenIgnoringThePrefixAndTitleStartsWithThe_ShouldMatchOnTheStrippedTitle()
|
||||
{
|
||||
// Arrange
|
||||
SeedBooks(("The Art of War", null), ("Beneath the Surface", null));
|
||||
BookAlphaFilterSpecification specification = new("a", true);
|
||||
|
||||
// Act
|
||||
List<string> result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)];
|
||||
|
||||
// Assert
|
||||
Assert.Equal(["The Art of War"], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToExpression_WhenNotIgnoringThePrefixAndTitleStartsWithThe_ShouldNotMatchOnTheStrippedTitle()
|
||||
{
|
||||
// Arrange
|
||||
SeedBooks(("The Art of War", null), ("Beneath the Surface", null));
|
||||
BookAlphaFilterSpecification specification = new("a", false);
|
||||
|
||||
// Act
|
||||
List<BookEntity> result = [.. _context.Books.Where(specification.ToExpression())];
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds books with the provided titles.
|
||||
/// </summary>
|
||||
/// <param name="books">The title and original title pairs of the books to seed.</param>
|
||||
/// <returns>The seeded <see cref="BookEntity"/> instances.</returns>
|
||||
private List<BookEntity> SeedBooks(params (string Title, string? OriginalTitle)[] books)
|
||||
{
|
||||
List<BookEntity> entities = [];
|
||||
foreach ((string title, string? originalTitle) in books)
|
||||
entities.Add(_bookEntityFixture.Create(title: title, originalTitle: originalTitle, includeMetadata: false));
|
||||
_context.Books.AddRange(entities);
|
||||
_context.SaveChanges();
|
||||
return entities;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context and its underlying connection.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
_connection.Dispose();
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,14 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Books.Specifications;
|
||||
using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Specifications;
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary.Specifications;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookSearchSpecification"/> class.
|
||||
+51
-13
@@ -1,9 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -18,7 +19,6 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoun
|
||||
public class BookTests
|
||||
{
|
||||
private readonly BookFixture _bookFixture = new();
|
||||
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidData_ShouldCreateBook()
|
||||
@@ -38,16 +38,16 @@ public class BookTests
|
||||
{
|
||||
// Arrange
|
||||
Book book = _bookFixture.Create();
|
||||
MediaContributorId firstContributorId = _mediaContributorIdFixture.Create();
|
||||
MediaContributorId secondContributorId = _mediaContributorIdFixture.Create();
|
||||
BookMediaContributor firstContributor = CreateAuthorContributor();
|
||||
BookMediaContributor secondContributor = CreateAuthorContributor();
|
||||
|
||||
// Act
|
||||
book.UpdateContributors([firstContributorId, secondContributorId]);
|
||||
book.UpdateContributors([firstContributor, secondContributor]);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, book.Contributors.Count);
|
||||
Assert.Contains(book.Contributors, contributorId => contributorId == firstContributorId);
|
||||
Assert.Contains(book.Contributors, contributorId => contributorId == secondContributorId);
|
||||
Assert.Contains(book.Contributors, contributor => contributor == firstContributor);
|
||||
Assert.Contains(book.Contributors, contributor => contributor == secondContributor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -55,16 +55,45 @@ public class BookTests
|
||||
{
|
||||
// Arrange
|
||||
Book book = _bookFixture.Create();
|
||||
book.UpdateContributors([_mediaContributorIdFixture.Create()]);
|
||||
MediaContributorId replacementContributorId = _mediaContributorIdFixture.Create();
|
||||
book.UpdateContributors([CreateAuthorContributor()]);
|
||||
BookMediaContributor replacementContributor = CreateAuthorContributor();
|
||||
|
||||
// Act
|
||||
book.UpdateContributors([replacementContributorId]);
|
||||
book.UpdateContributors([replacementContributor]);
|
||||
|
||||
// Assert
|
||||
// the previous contributors are replaced, not appended
|
||||
MediaContributorId contributorId = Assert.Single(book.Contributors);
|
||||
Assert.Equal(replacementContributorId, contributorId);
|
||||
BookMediaContributor contributor = Assert.Single(book.Contributors);
|
||||
Assert.Equal(replacementContributor, contributor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenContributorsContainDuplicates_ShouldKeepOnlyUniqueContributors()
|
||||
{
|
||||
// Arrange
|
||||
BookMediaContributor contributor = CreateAuthorContributor();
|
||||
|
||||
// Act
|
||||
Book book = _bookFixture.Create(contributors: [contributor, contributor]);
|
||||
|
||||
// Assert
|
||||
BookMediaContributor storedContributor = Assert.Single(book.Contributors);
|
||||
Assert.Equal(contributor, storedContributor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UpdateContributors_WhenCalledWithDuplicates_ShouldKeepOnlyUniqueContributors()
|
||||
{
|
||||
// Arrange
|
||||
Book book = _bookFixture.Create();
|
||||
BookMediaContributor contributor = CreateAuthorContributor();
|
||||
|
||||
// Act
|
||||
book.UpdateContributors([contributor, contributor]);
|
||||
|
||||
// Assert
|
||||
BookMediaContributor storedContributor = Assert.Single(book.Contributors);
|
||||
Assert.Equal(contributor, storedContributor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -229,4 +258,13 @@ public class BookTests
|
||||
Assert.False(hasMetadataProvider);
|
||||
Assert.False(hasCoverImagePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="BookMediaContributor"/> of a random media contributor playing the Author role.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="BookMediaContributor"/>.</returns>
|
||||
private static BookMediaContributor CreateAuthorContributor()
|
||||
{
|
||||
return BookMediaContributor.Create(MediaContributorId.CreateUnique(), MediaContributorRole.Author).Value;
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookLibraryService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookLibraryServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public void Books_WhenAccessed_ShouldThrowNotImplementedException()
|
||||
{
|
||||
// Arrange
|
||||
BookLibraryService sut = new();
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<NotImplementedException>(() => sut.Books);
|
||||
}
|
||||
}
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookLibraryId"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookLibraryIdTests
|
||||
{
|
||||
private readonly BookLibraryIdFixture _bookLibraryIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue()
|
||||
{
|
||||
// Act
|
||||
Result<BookLibraryId> result = BookLibraryId.CreateUnique();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotEqual(default, result.Value.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<BookLibraryId> result = BookLibraryId.Create(value);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(value, result.Value.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValue_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid value = Guid.NewGuid();
|
||||
BookLibraryId firstId = _bookLibraryIdFixture.Create(value);
|
||||
BookLibraryId secondId = _bookLibraryIdFixture.Create(value);
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentValue_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
BookLibraryId firstId = _bookLibraryIdFixture.Create();
|
||||
BookLibraryId secondId = _bookLibraryIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool result = firstId.Equals(secondId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -58,6 +58,7 @@ public class BooksFileSystemDiscoveryJobTests
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
@@ -84,7 +85,7 @@ public class BooksFileSystemDiscoveryJobTests
|
||||
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve the library"));
|
||||
|
||||
// Act
|
||||
@@ -103,7 +104,7 @@ public class BooksFileSystemDiscoveryJobTests
|
||||
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(null));
|
||||
|
||||
// Act
|
||||
|
||||
+1
@@ -58,6 +58,7 @@ public class BookReadingServiceTests
|
||||
_mockPluginManager.GetPlugins().Returns([_mockPlugin]);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
|
||||
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository);
|
||||
LibraryBookReaderConfigurationEntity enabledConfiguration = _configurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true);
|
||||
|
||||
+6
-12
@@ -210,33 +210,27 @@ public class CalibreMapperTests
|
||||
|
||||
MediaContributorDto author = result.Contributors[0];
|
||||
Assert.Equal("Test Author", author.Name!.DisplayName);
|
||||
Assert.Equal("Author", author.Role!.Name);
|
||||
Assert.Equal(MediaContributorRoleCategory.Author, author.Role.Category);
|
||||
Assert.Equal(MediaContributorRole.Author, author.Role);
|
||||
|
||||
MediaContributorDto coAuthor = result.Contributors[1];
|
||||
Assert.Equal("Co Author", coAuthor.Name!.DisplayName);
|
||||
Assert.Equal("Author", coAuthor.Role!.Name);
|
||||
Assert.Equal(MediaContributorRoleCategory.Author, coAuthor.Role.Category);
|
||||
Assert.Equal(MediaContributorRole.Author, coAuthor.Role);
|
||||
|
||||
MediaContributorDto translator = result.Contributors[2];
|
||||
Assert.Equal("Test Translator", translator.Name!.DisplayName);
|
||||
Assert.Equal("trl", translator.Role!.Name);
|
||||
Assert.Equal(MediaContributorRoleCategory.Translator, translator.Role.Category);
|
||||
Assert.Equal(MediaContributorRole.Translator, translator.Role);
|
||||
|
||||
MediaContributorDto illustrator = result.Contributors[3];
|
||||
Assert.Equal("Test Illustrator", illustrator.Name!.DisplayName);
|
||||
Assert.Equal("ill", illustrator.Role!.Name);
|
||||
Assert.Equal(MediaContributorRoleCategory.Illustrator, illustrator.Role.Category);
|
||||
Assert.Equal(MediaContributorRole.Illustrator, illustrator.Role);
|
||||
|
||||
MediaContributorDto production = result.Contributors[4];
|
||||
Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", production.Name!.DisplayName);
|
||||
Assert.Equal("bkp", production.Role!.Name);
|
||||
Assert.Equal(MediaContributorRoleCategory.Publisher, production.Role.Category);
|
||||
Assert.Equal(MediaContributorRole.Publisher, production.Role);
|
||||
|
||||
MediaContributorDto misc = result.Contributors[5];
|
||||
Assert.Equal("Misc Contributor", misc.Name!.DisplayName);
|
||||
Assert.Equal("Contributor", misc.Role!.Name);
|
||||
Assert.Equal(MediaContributorRoleCategory.Other, misc.Role.Category);
|
||||
Assert.Equal(MediaContributorRole.Other, misc.Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+60
-66
@@ -170,20 +170,18 @@ public class OpenLibraryMapperTests
|
||||
oclc: ["123456789"]);
|
||||
|
||||
// Act
|
||||
AddBookRequest result = OpenLibraryMapper.MapSearchCandidate(lookup, document);
|
||||
BookMetadataDto result = OpenLibraryMapper.MapSearchCandidate(lookup, document);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(lookup.LibraryId, result.LibraryId);
|
||||
Assert.Equal(lookup.Path, result.Path);
|
||||
Assert.Equal("Search Title", result.Metadata!.Title);
|
||||
Assert.Equal(2003, result.Metadata.ReleaseInfo!.OriginalReleaseYear);
|
||||
Assert.Equal("Search Publisher", result.Metadata.Publisher);
|
||||
Assert.Equal(250, result.Metadata.PageCount);
|
||||
Assert.Contains(result.Metadata.Genres!, genre => genre.Name == "Science fiction");
|
||||
Assert.DoesNotContain(result.Metadata.Genres!, genre => genre.Name == "Space");
|
||||
Assert.Contains(result.Metadata.Tags!, tag => tag.Name == "Science fiction");
|
||||
Assert.Contains(result.Metadata.Tags!, tag => tag.Name == "Space");
|
||||
Assert.Null(result.Metadata.ReleaseInfo.ReleaseCountry);
|
||||
Assert.Equal("Search Title", result.Title);
|
||||
Assert.Equal(2003, result.ReleaseInfo!.OriginalReleaseYear);
|
||||
Assert.Equal("Search Publisher", result.Publisher);
|
||||
Assert.Equal(250, result.PageCount);
|
||||
Assert.Contains(result.Genres!, genre => genre.Name == "Science fiction");
|
||||
Assert.DoesNotContain(result.Genres!, genre => genre.Name == "Space");
|
||||
Assert.Contains(result.Tags!, tag => tag.Name == "Science fiction");
|
||||
Assert.Contains(result.Tags!, tag => tag.Name == "Space");
|
||||
Assert.Null(result.ReleaseInfo.ReleaseCountry);
|
||||
BookRatingDto rating = Assert.Single(result.Ratings!);
|
||||
Assert.Equal(4.1m, rating.Value);
|
||||
Assert.Equal(5m, rating.MaxValue);
|
||||
@@ -192,8 +190,8 @@ public class OpenLibraryMapperTests
|
||||
Assert.Equal("79042755", result.LCCN);
|
||||
Assert.Equal("123456789", result.OCLCNumber);
|
||||
Assert.Equal("OL12345W", result.OpenLibraryId);
|
||||
Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Search Author" && contributor.Role!.Name == "Author");
|
||||
Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Search Author" && contributor.Role == MediaContributorRole.Author);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -235,33 +233,31 @@ public class OpenLibraryMapperTests
|
||||
OpenLibraryRatingsResponse ratings = _ratingsResponseFixture.Create(_ratingSummaryResponseFixture.Create(average: 4.2m, count: 100));
|
||||
|
||||
// Act
|
||||
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, work, [author], ratings);
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, work, [author], ratings);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(lookup.LibraryId, result.LibraryId);
|
||||
Assert.Equal(lookup.Path, result.Path);
|
||||
Assert.Equal("Edition Title", result.Metadata!.Title);
|
||||
Assert.Equal("Original Title", result.Metadata.OriginalTitle);
|
||||
Assert.Equal("A work description", result.Metadata.Description);
|
||||
Assert.Equal(new DateOnly(1987, 6, 1), result.Metadata.ReleaseInfo!.OriginalReleaseDate);
|
||||
Assert.Equal(1987, result.Metadata.ReleaseInfo.OriginalReleaseYear);
|
||||
Assert.Equal(new DateOnly(2010, 5, 1), result.Metadata.ReleaseInfo.ReReleaseDate);
|
||||
Assert.Equal(2010, result.Metadata.ReleaseInfo.ReReleaseYear);
|
||||
Assert.Null(result.Metadata.ReleaseInfo.ReleaseCountry);
|
||||
Assert.Equal("First Edition", result.Metadata.ReleaseInfo.ReleaseVersion);
|
||||
GenreDto genre = Assert.Single(result.Metadata.Genres!);
|
||||
Assert.Equal("Edition Title", result.Title);
|
||||
Assert.Equal("Original Title", result.OriginalTitle);
|
||||
Assert.Equal("A work description", result.Description);
|
||||
Assert.Equal(new DateOnly(1987, 6, 1), result.ReleaseInfo!.OriginalReleaseDate);
|
||||
Assert.Equal(1987, result.ReleaseInfo.OriginalReleaseYear);
|
||||
Assert.Equal(new DateOnly(2010, 5, 1), result.ReleaseInfo.ReReleaseDate);
|
||||
Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear);
|
||||
Assert.Null(result.ReleaseInfo.ReleaseCountry);
|
||||
Assert.Equal("First Edition", result.ReleaseInfo.ReleaseVersion);
|
||||
GenreDto genre = Assert.Single(result.Genres!);
|
||||
Assert.Equal("Fantasy", genre.Name);
|
||||
Assert.Equal(3, result.Metadata.Tags!.Count);
|
||||
Assert.Contains(result.Metadata.Tags, tag => tag.Name == "Science fiction");
|
||||
Assert.Contains(result.Metadata.Tags, tag => tag.Name == "History");
|
||||
Assert.Contains(result.Metadata.Tags, tag => tag.Name == "Space");
|
||||
Assert.Equal("en", result.Metadata.Language!.LanguageCode);
|
||||
Assert.False(string.IsNullOrWhiteSpace(result.Metadata.Language.LanguageName));
|
||||
Assert.Equal("fre", result.Metadata.OriginalLanguage!.LanguageCode);
|
||||
Assert.Equal("fre", result.Metadata.OriginalLanguage.LanguageName);
|
||||
Assert.Null(result.Metadata.OriginalLanguage.NativeName);
|
||||
Assert.Equal("Publisher Co", result.Metadata.Publisher);
|
||||
Assert.Equal(320, result.Metadata.PageCount);
|
||||
Assert.Equal(3, result.Tags!.Count);
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "Science fiction");
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "History");
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "Space");
|
||||
Assert.Equal("en", result.Language!.LanguageCode);
|
||||
Assert.False(string.IsNullOrWhiteSpace(result.Language.LanguageName));
|
||||
Assert.Equal("fre", result.OriginalLanguage!.LanguageCode);
|
||||
Assert.Equal("fre", result.OriginalLanguage.LanguageName);
|
||||
Assert.Null(result.OriginalLanguage.NativeName);
|
||||
Assert.Equal("Publisher Co", result.Publisher);
|
||||
Assert.Equal(320, result.PageCount);
|
||||
Assert.Equal(BookFormat.Hardcover, result.Format);
|
||||
Assert.Equal("First Edition", result.Edition);
|
||||
Assert.Equal(3, result.VolumeNumber);
|
||||
@@ -275,10 +271,10 @@ public class OpenLibraryMapperTests
|
||||
Assert.Equal("gid", result.GoogleBooksId);
|
||||
Assert.Equal("bnid", result.BarnesAndNobleId);
|
||||
Assert.Equal("apid", result.AppleBooksId);
|
||||
Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
|
||||
Assert.Contains(result.ISBNs!, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10);
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author" && contributor.Name.LegalName == "Test Personal Name" && contributor.Role!.Name == "Author");
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role!.Name == "Illustrator" && contributor.Role.Category == MediaContributorRoleCategory.Illustrator);
|
||||
Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
|
||||
Assert.Contains(result.Isbns!, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10);
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author" && contributor.Name.LegalName == "Test Personal Name" && contributor.Role == MediaContributorRole.Author);
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role == MediaContributorRole.Illustrator);
|
||||
BookRatingDto mappedRating = Assert.Single(result.Ratings!);
|
||||
Assert.Equal(4.2m, mappedRating.Value);
|
||||
Assert.Equal(5m, mappedRating.MaxValue);
|
||||
@@ -294,13 +290,13 @@ public class OpenLibraryMapperTests
|
||||
OpenLibraryWorkResponse work = _workResponseFixture.Create(subjects: ["Science fiction", "History", "Space"]);
|
||||
|
||||
// Act
|
||||
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null);
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Metadata!.Genres!.Count);
|
||||
Assert.Contains(result.Metadata.Genres, genre => genre.Name == "Science fiction");
|
||||
Assert.Contains(result.Metadata.Genres, genre => genre.Name == "History");
|
||||
Assert.DoesNotContain(result.Metadata.Genres, genre => genre.Name == "Space");
|
||||
Assert.Equal(2, result.Genres!.Count);
|
||||
Assert.Contains(result.Genres, genre => genre.Name == "Science fiction");
|
||||
Assert.Contains(result.Genres, genre => genre.Name == "History");
|
||||
Assert.DoesNotContain(result.Genres, genre => genre.Name == "Space");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -311,11 +307,11 @@ public class OpenLibraryMapperTests
|
||||
OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create(firstPublishYear: 2001);
|
||||
|
||||
// Act
|
||||
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback);
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2001, result.Metadata!.ReleaseInfo!.OriginalReleaseYear);
|
||||
Assert.Null(result.Metadata.ReleaseInfo.OriginalReleaseDate);
|
||||
Assert.Equal(2001, result.ReleaseInfo!.OriginalReleaseYear);
|
||||
Assert.Null(result.ReleaseInfo.OriginalReleaseDate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -326,13 +322,13 @@ public class OpenLibraryMapperTests
|
||||
OpenLibraryEditionResponse edition = _editionResponseFixture.Create(languages: [_keyReferenceResponseFixture.Create(key: "/languages/xxq")]);
|
||||
|
||||
// Act
|
||||
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.Metadata!.Language);
|
||||
Assert.Equal("xxq", result.Metadata.Language!.LanguageCode);
|
||||
Assert.Equal("xxq", result.Metadata.Language.LanguageName);
|
||||
Assert.Null(result.Metadata.Language.NativeName);
|
||||
Assert.NotNull(result.Language);
|
||||
Assert.Equal("xxq", result.Language!.LanguageCode);
|
||||
Assert.Equal("xxq", result.Language.LanguageName);
|
||||
Assert.Null(result.Language.NativeName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -343,10 +339,10 @@ public class OpenLibraryMapperTests
|
||||
OpenLibraryWorkResponse work = _workResponseFixture.Create(description: JsonDocument.Parse("\"A plain description\"").RootElement);
|
||||
|
||||
// Act
|
||||
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null);
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("A plain description", result.Metadata!.Description);
|
||||
Assert.Equal("A plain description", result.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -356,17 +352,15 @@ public class OpenLibraryMapperTests
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(isbn: "978-0-306-40615-7");
|
||||
|
||||
// Act
|
||||
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, null);
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(lookup.LibraryId, result.LibraryId);
|
||||
Assert.Equal(lookup.Path, result.Path);
|
||||
Assert.NotNull(result.Metadata);
|
||||
Assert.Null(result.Metadata!.Title);
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.Title);
|
||||
Assert.Null(result.Format);
|
||||
Assert.Null(result.Edition);
|
||||
Assert.Null(result.OpenLibraryId);
|
||||
Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157");
|
||||
Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157");
|
||||
Assert.Empty(result.Ratings!);
|
||||
Assert.Empty(result.Contributors!);
|
||||
}
|
||||
@@ -379,7 +373,7 @@ public class OpenLibraryMapperTests
|
||||
OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create(ratingsAverage: 3.5m, ratingsCount: 10);
|
||||
|
||||
// Act
|
||||
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback);
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback);
|
||||
|
||||
// Assert
|
||||
BookRatingDto rating = Assert.Single(result.Ratings!);
|
||||
@@ -395,7 +389,7 @@ public class OpenLibraryMapperTests
|
||||
OpenLibraryEditionResponse edition = _editionResponseFixture.Create(series: ["Book 2 of the trilogy"]);
|
||||
|
||||
// Act
|
||||
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.VolumeNumber);
|
||||
@@ -420,7 +414,7 @@ public class OpenLibraryMapperTests
|
||||
oclc: ["888888"]);
|
||||
|
||||
// Act
|
||||
AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null, fallback);
|
||||
BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null, fallback);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("B000002", result.ASIN);
|
||||
|
||||
+8
-8
@@ -339,12 +339,12 @@ public class OpenLibraryBookMetadataProviderTests
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
AddBookRequest? result = await sut.GetBookAsync(lookup);
|
||||
BookMetadataDto? result = await sut.GetBookAsync(lookup);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Edition Title", result!.Metadata!.Title);
|
||||
Assert.Equal("A work description", result.Metadata.Description);
|
||||
Assert.Equal("Edition Title", result.Title);
|
||||
Assert.Equal("A work description", result.Description);
|
||||
Assert.Equal("OL100M", result.OpenLibraryId);
|
||||
Assert.Equal(BookFormat.Hardcover, result.Format);
|
||||
Assert.Equal(3, result.VolumeNumber);
|
||||
@@ -370,11 +370,11 @@ public class OpenLibraryBookMetadataProviderTests
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
AddBookRequest? result = await sut.GetBookAsync(lookup);
|
||||
BookMetadataDto? result = await sut.GetBookAsync(lookup);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Work Title", result!.Metadata!.Title);
|
||||
Assert.Equal("Work Title", result.Title);
|
||||
Assert.Equal("OL200W", result.OpenLibraryId);
|
||||
}
|
||||
|
||||
@@ -389,11 +389,11 @@ public class OpenLibraryBookMetadataProviderTests
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
AddBookRequest? result = await sut.GetBookAsync(lookup);
|
||||
BookMetadataDto? result = await sut.GetBookAsync(lookup);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Fallback Edition", result!.Metadata!.Title);
|
||||
Assert.Equal("Fallback Edition", result.Title);
|
||||
Assert.Equal("OL600M", result.OpenLibraryId);
|
||||
Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/books/OL600M.json");
|
||||
}
|
||||
@@ -408,7 +408,7 @@ public class OpenLibraryBookMetadataProviderTests
|
||||
OpenLibraryBookMetadataProvider sut = CreateProvider(handler);
|
||||
|
||||
// Act
|
||||
AddBookRequest? result = await sut.GetBookAsync(lookup);
|
||||
BookMetadataDto? result = await sut.GetBookAsync(lookup);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
|
||||
+9
-24
@@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -49,7 +50,7 @@ public class AddBookEndpointTests
|
||||
BookResponse expectedResponse = _bookResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
ConfigureRequest(libraryId.ToString());
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -86,7 +87,7 @@ public class AddBookEndpointTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToHandler()
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -94,7 +95,7 @@ public class AddBookEndpointTests
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequest(libraryId.ToString());
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -142,10 +143,10 @@ public class AddBookEndpointTests
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
AddBookRequest request = _addBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Error.Validation(description: "LibraryIdCannotBeEmpty");
|
||||
Error validationError = Errors.Library.LibraryIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
ConfigureRequest(libraryId.ToString());
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -157,6 +158,7 @@ public class AddBookEndpointTests
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
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"]);
|
||||
@@ -170,7 +172,7 @@ public class AddBookEndpointTests
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequest("not-a-library-guid");
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -189,7 +191,7 @@ public class AddBookEndpointTests
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<AddBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequestWithoutLibraryId();
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -199,21 +201,4 @@ public class AddBookEndpointTests
|
||||
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");
|
||||
}
|
||||
}
|
||||
+100
-22
@@ -1,11 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -27,7 +25,6 @@ public class GetReadingAvailabilityEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>> _mockHandler;
|
||||
private readonly GetReadingAvailabilityEndpoint _sut;
|
||||
private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new();
|
||||
private readonly ReadingAvailabilityResponseFixture _readingAvailabilityResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -36,21 +33,24 @@ public class GetReadingAvailabilityEndpointTests
|
||||
public GetReadingAvailabilityEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>>>();
|
||||
_sut = Factory.Create<GetReadingAvailabilityEndpoint>(_mockHandler);
|
||||
_sut = FastEndpoints.Factory.Create<GetReadingAvailabilityEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingAvailability()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null);
|
||||
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: bookId, libraryId: libraryId, isAvailable: true, errorCode: null);
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ReadingAvailabilityResponse> okResult = Assert.IsType<Ok<ReadingAvailabilityResponse>>(result);
|
||||
@@ -61,14 +61,17 @@ public class GetReadingAvailabilityEndpointTests
|
||||
public async Task ExecuteAsync_WhenBookIsNotAvailable_ShouldReturnOkResultWithUnavailableReadingAvailability()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: false, errorCode: "ReaderDisabled");
|
||||
ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: bookId, libraryId: libraryId, isAvailable: false, errorCode: "ReaderDisabled");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ReadingAvailabilityResponse> okResult = Assert.IsType<Ok<ReadingAvailabilityResponse>>(result);
|
||||
@@ -78,17 +81,20 @@ public class GetReadingAvailabilityEndpointTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Reading.BookNotFound", "BookNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
@@ -98,22 +104,91 @@ public class GetReadingAvailabilityEndpointTests
|
||||
Assert.Equal("BookNotFound", problemResult.ProblemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingAvailabilityQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReadingAvailabilityResponse response = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null);
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(response));
|
||||
.Returns(Result.From(_readingAvailabilityResponseFixture.Create(bookId: bookId, libraryId: libraryId, isAvailable: true, errorCode: null)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingAvailabilityQuery>(query => query.BookId == request.BookId),
|
||||
Arg.Is<GetReadingAvailabilityQuery>(query => query.LibraryId == libraryId.ToString() && query.BookId == bookId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_readingAvailabilityResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingAvailabilityQuery>(query => query.LibraryId == "not-a-library-guid" && query.BookId == "not-a-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingAvailabilityQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_readingAvailabilityResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("bookId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingAvailabilityQuery>(query => query.LibraryId == null && query.BookId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
@@ -121,7 +196,8 @@ public class GetReadingAvailabilityEndpointTests
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
@@ -132,11 +208,13 @@ public class GetReadingAvailabilityEndpointTests
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null));
|
||||
return Result.From(_readingAvailabilityResponseFixture.Create());
|
||||
}, info.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
+92
-17
@@ -1,11 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -27,7 +25,6 @@ public class GetReadingManifestEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>> _mockHandler;
|
||||
private readonly GetReadingManifestEndpoint _sut;
|
||||
private readonly GetReadingManifestRequestFixture _getReadingManifestRequestFixture = new();
|
||||
private readonly ReadingManifestResponseFixture _readingManifestResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -36,21 +33,24 @@ public class GetReadingManifestEndpointTests
|
||||
public GetReadingManifestEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>>>();
|
||||
_sut = Factory.Create<GetReadingManifestEndpoint>(_mockHandler);
|
||||
_sut = FastEndpoints.Factory.Create<GetReadingManifestEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingManifest()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ReadingManifestResponse> okResult = Assert.IsType<Ok<ReadingManifestResponse>>(result);
|
||||
@@ -58,17 +58,20 @@ public class GetReadingManifestEndpointTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Reading.BookNotFound", "BookNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
@@ -78,22 +81,91 @@ public class GetReadingManifestEndpointTests
|
||||
Assert.Equal("BookNotFound", problemResult.ProblemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingManifestQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReadingManifestResponse response = _readingManifestResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(response));
|
||||
.Returns(Result.From(_readingManifestResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingManifestQuery>(query => query.BookId == request.BookId),
|
||||
Arg.Is<GetReadingManifestQuery>(query => query.LibraryId == libraryId.ToString() && query.BookId == bookId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_readingManifestResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingManifestQuery>(query => query.LibraryId == "not-a-library-guid" && query.BookId == "not-a-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingManifestQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_readingManifestResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("bookId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingManifestQuery>(query => query.LibraryId == null && query.BookId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
@@ -101,7 +173,8 @@ public class GetReadingManifestEndpointTests
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
@@ -114,9 +187,11 @@ public class GetReadingManifestEndpointTests
|
||||
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_readingManifestResponseFixture.Create());
|
||||
}, info.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
+111
-19
@@ -1,11 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -27,7 +25,6 @@ public class GetReadingResourceEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>> _mockHandler;
|
||||
private readonly GetReadingResourceEndpoint _sut;
|
||||
private readonly GetReadingResourceRequestFixture _getReadingResourceRequestFixture = new();
|
||||
private readonly ReadingResourceDataDtoFixture _readingResourceDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -36,21 +33,25 @@ public class GetReadingResourceEndpointTests
|
||||
public GetReadingResourceEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>>>();
|
||||
_sut = Factory.Create<GetReadingResourceEndpoint>(_mockHandler);
|
||||
_sut = FastEndpoints.Factory.Create<GetReadingResourceEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnBytesResultWithResourceData()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
FileContentHttpResult bytesResult = Assert.IsType<FileContentHttpResult>(result);
|
||||
@@ -59,17 +60,21 @@ public class GetReadingResourceEndpointTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Reading.ResourceNotFound", "ResourceNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
@@ -79,6 +84,36 @@ public class GetReadingResourceEndpointTests
|
||||
Assert.Equal("ResourceNotFound", problemResult.ProblemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("image/png", "image/png")] // a non-svg image is inert content
|
||||
[InlineData("image/svg+xml", "application/octet-stream")] // an svg can be executed, so it is served as an opaque download
|
||||
@@ -95,14 +130,18 @@ public class GetReadingResourceEndpointTests
|
||||
public async Task ExecuteAsync_WhenServingAResource_ShouldUseTheSafeContentType(string mimeType, string expectedContentType)
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReadingResourceDataDto response = new(Guid.NewGuid().ToByteArray(), mimeType);
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(response));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
FileContentHttpResult bytesResult = Assert.IsType<FileContentHttpResult>(result);
|
||||
@@ -115,18 +154,67 @@ public class GetReadingResourceEndpointTests
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingResourceQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReadingResourceDataDto response = _readingResourceDataDtoFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(response));
|
||||
.Returns(Result.From(_readingResourceDataDtoFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingResourceQuery>(query => query.BookId == request.BookId && query.ResourceKey == request.ResourceKey),
|
||||
Arg.Is<GetReadingResourceQuery>(query =>
|
||||
query.LibraryId == libraryId.ToString() &&
|
||||
query.BookId == bookId.ToString() &&
|
||||
query.ResourceKey == "cover-image"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_readingResourceDataDtoFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
|
||||
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingResourceQuery>(query =>
|
||||
query.LibraryId == "not-a-library-guid" &&
|
||||
query.BookId == "not-a-guid" &&
|
||||
query.ResourceKey == "cover-image"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingResourceQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_readingResourceDataDtoFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("bookId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("resourceKey");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingResourceQuery>(query => query.LibraryId == null && query.BookId == null && query.ResourceKey == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
@@ -134,7 +222,8 @@ public class GetReadingResourceEndpointTests
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
@@ -147,9 +236,12 @@ public class GetReadingResourceEndpointTests
|
||||
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_readingResourceDataDtoFixture.Create());
|
||||
}, info.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image";
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
+107
-19
@@ -1,11 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -27,7 +25,6 @@ public class GetReadingSectionEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>> _mockHandler;
|
||||
private readonly GetReadingSectionEndpoint _sut;
|
||||
private readonly GetReadingSectionRequestFixture _getReadingSectionRequestFixture = new();
|
||||
private readonly ReadingSectionDtoFixture _readingSectionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -36,21 +33,25 @@ public class GetReadingSectionEndpointTests
|
||||
public GetReadingSectionEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>>>();
|
||||
_sut = Factory.Create<GetReadingSectionEndpoint>(_mockHandler);
|
||||
_sut = FastEndpoints.Factory.Create<GetReadingSectionEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingSection()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: request.LocationRef);
|
||||
ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: "chapter-1");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ReadingSectionDto> okResult = Assert.IsType<Ok<ReadingSectionDto>>(result);
|
||||
@@ -58,17 +59,21 @@ public class GetReadingSectionEndpointTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Reading.SectionNotFound", "SectionNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
@@ -78,22 +83,101 @@ public class GetReadingSectionEndpointTests
|
||||
Assert.Equal("SectionNotFound", problemResult.ProblemDetails.Detail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingSectionQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReadingSectionDto response = _readingSectionDtoFixture.Create(locationRef: request.LocationRef);
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(response));
|
||||
.Returns(Result.From(_readingSectionDtoFixture.Create(locationRef: "chapter-1")));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingSectionQuery>(query => query.BookId == request.BookId && query.LocationRef == request.LocationRef),
|
||||
Arg.Is<GetReadingSectionQuery>(query =>
|
||||
query.LibraryId == libraryId.ToString() &&
|
||||
query.BookId == bookId.ToString() &&
|
||||
query.LocationRef == "chapter-1"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_readingSectionDtoFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
|
||||
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingSectionQuery>(query =>
|
||||
query.LibraryId == "not-a-library-guid" &&
|
||||
query.BookId == "not-a-guid" &&
|
||||
query.LocationRef == "chapter-1"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetReadingSectionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_readingSectionDtoFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("bookId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("locationRef");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetReadingSectionQuery>(query => query.LibraryId == null && query.BookId == null && query.LocationRef == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
@@ -101,7 +185,8 @@ public class GetReadingSectionEndpointTests
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
@@ -112,11 +197,14 @@ public class GetReadingSectionEndpointTests
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_readingSectionDtoFixture.Create(locationRef: request.LocationRef));
|
||||
return Result.From(_readingSectionDtoFixture.Create());
|
||||
}, info.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1";
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
+18
-29
@@ -5,6 +5,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -49,7 +50,8 @@ public class UpdateBookEndpointTests
|
||||
BookResponse expectedResponse = _bookResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
ConfigureRequest(libraryId.ToString(), routeId.ToString());
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -70,7 +72,8 @@ public class UpdateBookEndpointTests
|
||||
Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
ConfigureRequest(libraryId.ToString(), routeId.ToString());
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -94,10 +97,11 @@ public class UpdateBookEndpointTests
|
||||
Guid routeId = Guid.NewGuid();
|
||||
UpdateBookRequest request = _updateBookRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Error.Validation(description: "BookIdCannotBeEmpty");
|
||||
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
ConfigureRequest(libraryId.ToString(), routeId.ToString());
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -109,13 +113,14 @@ public class UpdateBookEndpointTests
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateBookCommandToHandler()
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateBookCommandToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
@@ -124,7 +129,8 @@ public class UpdateBookEndpointTests
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequest(libraryId.ToString(), routeId.ToString());
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -152,7 +158,8 @@ public class UpdateBookEndpointTests
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequest("not-a-library-guid", "not-a-guid");
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -171,7 +178,8 @@ public class UpdateBookEndpointTests
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_bookResponseFixture.Create()));
|
||||
ConfigureRequestWithoutIds();
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("bookId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
@@ -201,7 +209,8 @@ public class UpdateBookEndpointTests
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_bookResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
ConfigureRequest(libraryId.ToString(), routeId.ToString());
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
@@ -212,24 +221,4 @@ public class UpdateBookEndpointTests
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <c>libraryId</c> and <c>id</c> route values the endpoint reads the identifiers from.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The raw route value of the library Id.</param>
|
||||
/// <param name="bookId">The raw route value of the book Id.</param>
|
||||
private void ConfigureRequest(string libraryId, string bookId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId;
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Leaves the <c>libraryId</c> and <c>id</c> route values unset.
|
||||
/// </summary>
|
||||
private void ConfigureRequestWithoutIds()
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("bookId");
|
||||
}
|
||||
}
|
||||
+101
-44
@@ -1,6 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -22,110 +25,178 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenConten
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateBookCoverEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<UpdateBookCoverCommand, Result<string>> _mockHandler;
|
||||
private readonly ICommandHandler<UpdateBookCoverCommand, Result<UpdateBookCoverResponse>> _mockHandler;
|
||||
private readonly UpdateBookCoverEndpoint _sut;
|
||||
private readonly UpdateBookCoverResponseFixture _updateBookCoverResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public UpdateBookCoverEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<UpdateBookCoverCommand, Result<string>>>();
|
||||
_sut = Factory.Create<UpdateBookCoverEndpoint>(_mockHandler);
|
||||
_mockHandler = Substitute.For<ICommandHandler<UpdateBookCoverCommand, Result<UpdateBookCoverResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<UpdateBookCoverEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
string expectedPath = "/media/books/cover.jpg";
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedPath));
|
||||
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
|
||||
.Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: expectedPath)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
ConfigureForm([1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<string> okResult = Assert.IsType<Ok<string>>(result);
|
||||
Assert.Equal(expectedPath, okResult.Value);
|
||||
Ok<UpdateBookCoverResponse> okResult = Assert.IsType<Ok<UpdateBookCoverResponse>>(result);
|
||||
Assert.Equal(expectedPath, okResult.Value.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRouteIdAndFile_ShouldSendUpdateBookCoverCommand()
|
||||
public async Task ExecuteAsync_WhenCalledWithValidRouteIdsAndFile_ShouldSendUpdateBookCoverCommandToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/books/cover.jpg"));
|
||||
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
|
||||
.Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg")));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
ConfigureForm([1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCoverCommand>(command =>
|
||||
command.BookId == bookId &&
|
||||
command.LibraryId == libraryId.ToString() &&
|
||||
command.BookId == bookId.ToString() &&
|
||||
command.Cover != null &&
|
||||
command.FileName == "cover.jpg"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldSendCommandWithEmptyBookId()
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/books/cover.jpg"));
|
||||
ConfigureRequest("not-a-guid", [1, 2, 3], "cover.jpg");
|
||||
.Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg")));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid";
|
||||
ConfigureForm([1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCoverCommand>(command => command.BookId == Guid.Empty && command.Cover != null),
|
||||
Arg.Any<CancellationToken>());
|
||||
Arg.Is<UpdateBookCoverCommand>(command => command.LibraryId == "not-a-library-guid" && command.BookId == "not-a-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg")));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("bookId");
|
||||
ConfigureForm([1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCoverCommand>(command => command.LibraryId == null && command.BookId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFormHasNoFiles_ShouldSendCommandWithNullCover()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/books/cover.jpg"));
|
||||
ConfigureRequestWithoutFiles(bookId);
|
||||
.Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg")));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<Ok<string>>(result);
|
||||
Assert.IsType<Ok<UpdateBookCoverResponse>>(result);
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<UpdateBookCoverCommand>(command => command.BookId == bookId && command.Cover == null && command.FileName == null),
|
||||
Arg.Is<UpdateBookCoverCommand>(command => command.BookId == bookId.ToString() && command.Cover == null && command.FileName == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(validationError);
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
ConfigureForm([1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound");
|
||||
_mockHandler.HandleAsync(Arg.Any<UpdateBookCoverCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
ConfigureRequest(bookId, [1, 2, 3], "cover.jpg");
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString();
|
||||
ConfigureForm([1, 2, 3], "cover.jpg");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
@@ -138,14 +209,8 @@ public class UpdateBookCoverEndpointTests
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
private void ConfigureRequest(Guid bookId, byte[] content, string fileName)
|
||||
private void ConfigureForm(byte[] content, string fileName)
|
||||
{
|
||||
ConfigureRequest(bookId.ToString(), content, fileName);
|
||||
}
|
||||
|
||||
private void ConfigureRequest(string bookId, byte[] content, string fileName)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["id"] = bookId;
|
||||
MemoryStream coverStream = new(content);
|
||||
IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
@@ -153,12 +218,4 @@ public class UpdateBookCoverEndpointTests
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
private void ConfigureRequestWithoutFiles(Guid bookId)
|
||||
{
|
||||
_sut.HttpContext.Request.RouteValues["id"] = bookId.ToString();
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -59,7 +59,7 @@ public class GetLibraryBookReadersEndpointTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryBookReadersRequest request = _getLibraryBookReadersRequestFixture.Create();
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ public class SetLibraryBookReaderEnabledEndpointTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create();
|
||||
|
||||
+3
-3
@@ -44,7 +44,7 @@ public class GetBookDetailsEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.Id));
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.BookId));
|
||||
_mockApiHttpClient.GetAsync<BookDetailsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
|
||||
@@ -53,7 +53,7 @@ public class GetBookDetailsEndpointTests
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<BookDetailsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id)),
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Books.GET_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ public class GetBookDetailsEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
GetBookRequest request = _getBookRequestFixture.Create();
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.Id));
|
||||
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.BookId));
|
||||
_mockApiHttpClient.GetAsync<BookDetailsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedBook);
|
||||
|
||||
|
||||
+3
-4
@@ -63,8 +63,7 @@ public class GetLibraryItemsEndpointTests
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedBookLiteDto>(
|
||||
Arg.Is<string>(endpoint =>
|
||||
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) &&
|
||||
endpoint.Contains($"libraryId={request.LibraryId}") &&
|
||||
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE.Replace("{libraryId}", request.LibraryId.ToString()), StringComparison.OrdinalIgnoreCase) &&
|
||||
endpoint.Contains("currentPage=2") &&
|
||||
endpoint.Contains("perPage=48") &&
|
||||
endpoint.Contains("searchTerm=the%20hobbit") &&
|
||||
@@ -89,8 +88,8 @@ public class GetLibraryItemsEndpointTests
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedBookLiteDto>(
|
||||
Arg.Is<string>(endpoint =>
|
||||
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) &&
|
||||
endpoint.EndsWith($"libraryId={request.LibraryId}&shouldIgnoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) &&
|
||||
endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE.Replace("{libraryId}", request.LibraryId.ToString()), StringComparison.OrdinalIgnoreCase) &&
|
||||
endpoint.EndsWith("?shouldIgnoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) &&
|
||||
!endpoint.Contains("currentPage=") &&
|
||||
!endpoint.Contains("searchTerm=") &&
|
||||
!endpoint.Contains("sortBy=")),
|
||||
|
||||
Loaded 100 of 439 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user