mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 20:11:10 +00:00
Refactors the get books and get books lite slices across the stack
This commit is contained in:
1 parent
001146eefc
commit
1d35cd01db
44 files changed
+1681
-418
No files matched your search
+52
@@ -0,0 +1,52 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BookLiteRow"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookLiteRowFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="BookLiteRow"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the book.</param>
|
||||
/// <param name="title">Optional. The title of the book.</param>
|
||||
/// <param name="releaseYear">Optional. The release year of the book.</param>
|
||||
/// <param name="coverPath">Optional. The path of the cover image of the book.</param>
|
||||
/// <returns>The created <see cref="BookLiteRow"/>.</returns>
|
||||
public BookLiteRow Create(
|
||||
Guid? id = null,
|
||||
string? title = null,
|
||||
int? releaseYear = null,
|
||||
string? coverPath = null)
|
||||
{
|
||||
return new BookLiteRow
|
||||
{
|
||||
Id = id ?? _faker.Random.Guid(),
|
||||
Title = title ?? _faker.Lorem.Sentence(),
|
||||
ReleaseYear = releaseYear,
|
||||
CoverPath = coverPath
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="BookLiteRow"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="BookLiteRow"/> instances.</returns>
|
||||
public List<BookLiteRow> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+9
-14
@@ -1,10 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -19,36 +18,32 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.Bo
|
||||
public class GetBooksQueryFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get books.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved, taken from the route.</param>
|
||||
/// <param name="paginationData">Optional. The pagination data of the query.</param>
|
||||
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
||||
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
|
||||
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePaginationData">Whether the pagination data should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created query to get books.</returns>
|
||||
public GetBooksQuery Create(
|
||||
Guid? libraryId = null,
|
||||
string? libraryId = null,
|
||||
PaginationDataDto? paginationData = null,
|
||||
string? searchTerm = null,
|
||||
string? sortBy = null,
|
||||
SortOrder? sortOrder = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includePaginationData = true)
|
||||
{
|
||||
return new GetBooksQuery(
|
||||
includePaginationData ? paginationData ?? new PaginationDataDto
|
||||
{
|
||||
CurrentPage = _faker.Random.Number(1, 100),
|
||||
PerPage = _faker.Random.Number(1, 200)
|
||||
} : null,
|
||||
new LibraryFilterDto
|
||||
{
|
||||
LibraryId = libraryId ?? _faker.Random.Guid(),
|
||||
SearchTerm = searchTerm
|
||||
},
|
||||
includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null,
|
||||
includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null,
|
||||
searchTerm,
|
||||
sortBy,
|
||||
sortOrder ?? _faker.PickRandom<SortOrder>()
|
||||
);
|
||||
|
||||
+11
-16
@@ -1,10 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -19,42 +18,38 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.Bo
|
||||
public class GetBooksLiteQueryFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid query to get the lightweight details of books.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved, taken from the route.</param>
|
||||
/// <param name="paginationData">Optional. The pagination data of the query.</param>
|
||||
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
||||
/// <param name="filterAlphaKey">Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker.</param>
|
||||
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not.</param>
|
||||
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
|
||||
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePaginationData">Whether the pagination data should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created query to get the lightweight details of books.</returns>
|
||||
public GetBooksLiteQuery Create(
|
||||
Guid? libraryId = null,
|
||||
string? libraryId = null,
|
||||
PaginationDataDto? paginationData = null,
|
||||
string? searchTerm = null,
|
||||
string? filterAlphaKey = null,
|
||||
bool shouldIgnoreThePrefixForAlphaPicker = false,
|
||||
string? sortBy = null,
|
||||
SortOrder? sortOrder = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includePaginationData = true)
|
||||
{
|
||||
return new GetBooksLiteQuery(
|
||||
includePaginationData ? paginationData ?? new PaginationDataDto
|
||||
{
|
||||
CurrentPage = _faker.Random.Number(1, 100),
|
||||
PerPage = _faker.Random.Number(1, 200)
|
||||
} : null,
|
||||
new LibraryFilterDto
|
||||
{
|
||||
LibraryId = libraryId ?? _faker.Random.Guid(),
|
||||
SearchTerm = searchTerm,
|
||||
FilterAlphaKey = filterAlphaKey,
|
||||
ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker
|
||||
},
|
||||
includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null,
|
||||
includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null,
|
||||
searchTerm,
|
||||
filterAlphaKey,
|
||||
shouldIgnoreThePrefixForAlphaPicker,
|
||||
sortBy,
|
||||
sortOrder ?? _faker.PickRandom<SortOrder>()
|
||||
);
|
||||
|
||||
-4
@@ -2,7 +2,6 @@
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -21,7 +20,6 @@ public class GetBooksLiteRequestFixture
|
||||
/// <summary>
|
||||
/// Creates a <see cref="GetBooksLiteRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved.</param>
|
||||
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
|
||||
/// <param name="perPage">Optional. The maximum number of books to retrieve per page.</param>
|
||||
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
||||
@@ -33,7 +31,6 @@ public class GetBooksLiteRequestFixture
|
||||
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetBooksLiteRequest"/>.</returns>
|
||||
public GetBooksLiteRequest Create(
|
||||
Guid? libraryId = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
string? searchTerm = null,
|
||||
@@ -45,7 +42,6 @@ public class GetBooksLiteRequestFixture
|
||||
bool includePerPage = true)
|
||||
{
|
||||
return new GetBooksLiteRequest(
|
||||
LibraryId: libraryId ?? _faker.Random.Guid(),
|
||||
CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null,
|
||||
PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null,
|
||||
SearchTerm: searchTerm ?? _faker.Lorem.Word(),
|
||||
|
||||
-4
@@ -2,7 +2,6 @@
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
@@ -21,7 +20,6 @@ public class GetBooksRequestFixture
|
||||
/// <summary>
|
||||
/// Creates a <see cref="GetBooksRequest"/> with default or random values.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library whose books are retrieved.</param>
|
||||
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
|
||||
/// <param name="perPage">Optional. The maximum number of books to retrieve per page.</param>
|
||||
/// <param name="searchTerm">Optional. The search term used to filter results.</param>
|
||||
@@ -31,7 +29,6 @@ public class GetBooksRequestFixture
|
||||
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetBooksRequest"/>.</returns>
|
||||
public GetBooksRequest Create(
|
||||
Guid? libraryId = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
string? searchTerm = null,
|
||||
@@ -41,7 +38,6 @@ public class GetBooksRequestFixture
|
||||
bool includePerPage = true)
|
||||
{
|
||||
return new GetBooksRequest(
|
||||
LibraryId: libraryId ?? _faker.Random.Guid(),
|
||||
CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null,
|
||||
PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null,
|
||||
SearchTerm: searchTerm ?? _faker.Lorem.Word(),
|
||||
|
||||
+189
-10
@@ -77,7 +77,7 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -104,7 +104,7 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
await SeedBookAsync(libraryId, "The Two Towers");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}&searchTerm={Uri.EscapeDataString("Fellowship")}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?searchTerm={Uri.EscapeDataString("Fellowship")}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -127,7 +127,7 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
await SeedBookAsync(libraryId, "Book C");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}¤tPage=2&perPage=2");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -150,7 +150,7 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -172,7 +172,7 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.GetAsync($"/api/v1/books?libraryId={libraryId}", cts.Token)
|
||||
await _client.GetAsync($"/api/v1/libraries/{libraryId}/books", cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
@@ -190,7 +190,7 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/books?libraryId={libraryId}", cts.Token);
|
||||
await _client.GetAsync($"/api/v1/libraries/{libraryId}/books", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
@@ -205,7 +205,7 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
@@ -218,7 +218,7 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
@@ -235,7 +235,7 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/books?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/libraries/{libraryId}/books");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -254,7 +254,7 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
BookEntity seededBook = await SeedBookAsync(libraryId, "Tags And Ratings Book");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -269,6 +269,185 @@ public class GetBooksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory
|
||||
Assert.Equal(seededBook.Ratings.Single().Source, book.Ratings.Single().Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean
|
||||
// validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenSortedByTitleAscending_ShouldReturnBooksInAscendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
await SeedBookAsync(libraryId, "Book C");
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?sortBy=title&sortOrder=Ascending");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(new[] { "Book A", "Book B", "Book C" }, paginatedBooks!.Data.Select(book => book.Metadata.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenSortedByTitleDescending_ShouldReturnBooksInDescendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
await SeedBookAsync(libraryId, "Book C");
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?sortBy=title&sortOrder=Descending");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(new[] { "Book C", "Book B", "Book A" }, paginatedBooks!.Data.Select(book => book.Metadata.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenCurrentPageIsZero_ShouldReturnFirstPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?currentPage=0&perPage=1");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(1, paginatedBooks!.CurrentPage);
|
||||
Assert.Equal(1, paginatedBooks.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenPerPageIsZero_ShouldClampItToOne()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?currentPage=1&perPage=0");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(1, paginatedBooks!.PerPage);
|
||||
Assert.Equal(2, paginatedBooks.NumberOfPages);
|
||||
Assert.Single(paginatedBooks.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenCurrentPageExceedsNumberOfPages_ShouldReturnLastPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
await SeedBookAsync(libraryId, "Book C");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?currentPage=99&perPage=2");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(2, paginatedBooks!.CurrentPage);
|
||||
Assert.Equal(2, paginatedBooks.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenSortByIsUnknown_ShouldFallBackToTitleOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
await SeedBookAsync(libraryId, "Book C");
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?sortBy=unknownField&sortOrder=Ascending");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(new[] { "Book A", "Book B", "Book C" }, paginatedBooks!.Data.Select(book => book.Metadata.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenSearchTermMatchesNoBooks_ShouldReturnEmptyPaginatedResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books?searchTerm=nonexistent");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Empty(paginatedBooks!.Data);
|
||||
Assert.Equal(0, paginatedBooks.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{libraryId}/books");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="BookEntity"/> belonging to the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
|
||||
+206
-13
@@ -18,6 +18,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
|
||||
|
||||
@@ -69,7 +70,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -97,7 +98,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Racing");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=q");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?filterAlphaKey=q");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -120,7 +121,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Racing");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=q&shouldIgnoreThePrefixForAlphaPicker=true");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?filterAlphaKey=q&shouldIgnoreThePrefixForAlphaPicker=true");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -143,7 +144,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Brave New World");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=%23");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?filterAlphaKey=%23");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -166,7 +167,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Alpha");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=%2A");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?filterAlphaKey=%2A");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -189,7 +190,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Quiet Place");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&filterAlphaKey=r");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?filterAlphaKey=r");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -211,7 +212,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "The Two Towers");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString("Fellowship")}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?searchTerm={Uri.EscapeDataString("Fellowship")}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -234,7 +235,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Zoo");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString("Fellowship")}&filterAlphaKey=z");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?searchTerm={Uri.EscapeDataString("Fellowship")}&filterAlphaKey=z");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -256,7 +257,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Book C");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}¤tPage=2&perPage=2");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -279,7 +280,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -300,7 +301,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
@@ -313,7 +314,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
@@ -330,7 +331,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/books/lite?libraryId={libraryId}");
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/libraries/{libraryId}/books/lite");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -339,6 +340,198 @@ public class GetBooksLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
|
||||
Assert.Equal(1, paginatedBooks!.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/lite");
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean
|
||||
// validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenSortedByTitleAscending_ShouldReturnBooksInAscendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
await SeedBookAsync(libraryId, "Book C");
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?sortBy=title&sortOrder=Ascending");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(new[] { "Book A", "Book B", "Book C" }, paginatedBooks!.Data.Select(book => book.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenSortedByTitleDescending_ShouldReturnBooksInDescendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
await SeedBookAsync(libraryId, "Book C");
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?sortBy=title&sortOrder=Descending");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(new[] { "Book C", "Book B", "Book A" }, paginatedBooks!.Data.Select(book => book.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenSortByIsUnknown_ShouldFallBackToTitleOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
await SeedBookAsync(libraryId, "Book C");
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?sortBy=unknownField&sortOrder=Ascending");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(new[] { "Book A", "Book B", "Book C" }, paginatedBooks!.Data.Select(book => book.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenCurrentPageIsZero_ShouldReturnFirstPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?currentPage=0&perPage=1");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(1, paginatedBooks!.CurrentPage);
|
||||
Assert.Equal(1, paginatedBooks.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenPerPageIsZero_ShouldClampItToOne()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?currentPage=1&perPage=0");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(1, paginatedBooks!.PerPage);
|
||||
Assert.Equal(2, paginatedBooks.NumberOfPages);
|
||||
Assert.Single(paginatedBooks.Data);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenCurrentPageExceedsNumberOfPages_ShouldReturnLastPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
await SeedBookAsync(libraryId, "Book B");
|
||||
await SeedBookAsync(libraryId, "Book C");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?currentPage=99&perPage=2");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
PaginatedResponse<BookLiteResponse>? paginatedBooks = await response.Content.ReadFromJsonAsync<PaginatedResponse<BookLiteResponse>>(_jsonOptions);
|
||||
Assert.NotNull(paginatedBooks);
|
||||
Assert.Equal(2, paginatedBooks!.CurrentPage);
|
||||
Assert.Equal(2, paginatedBooks.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{libraryId}/books/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite", cts.Token)
|
||||
);
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
using CancellationTokenSource cts = new();
|
||||
|
||||
// Act & Assert
|
||||
Exception? exception = await Record.ExceptionAsync(async () =>
|
||||
{
|
||||
cts.Cancel();
|
||||
await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite", cts.Token);
|
||||
});
|
||||
Assert.IsType<TaskCanceledException>(exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="BookEntity"/> belonging to the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
|
||||
+59
-3
@@ -40,7 +40,7 @@ public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
public async Task GetBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/books");
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
@@ -52,7 +52,7 @@ public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
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("/api/v1/books", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
await _apiFactory.SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/books?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -84,6 +84,62 @@ public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooks_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
|
||||
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(requesterUsername);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetBooks_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books");
|
||||
|
||||
// Assert
|
||||
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the query
|
||||
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
|
||||
// or the injected payload.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
|
||||
+59
-3
@@ -41,7 +41,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDispo
|
||||
public async Task GetBooksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/books/lite");
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
@@ -53,7 +53,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDispo
|
||||
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("/api/v1/books/lite", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDispo
|
||||
await _apiFactory.SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -85,6 +85,62 @@ public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDispo
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksLite_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
|
||||
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(requesterUsername);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetBooksLite_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/lite");
|
||||
|
||||
// Assert
|
||||
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the query
|
||||
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
|
||||
// or the injected payload.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
|
||||
-69
@@ -365,73 +365,4 @@ public class BookEntityMappingTests
|
||||
Assert.Equal(paginatedBookEntities.Count, result.Count);
|
||||
Assert.Equal(paginatedBookEntities.NumberOfPages, result.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToLiteResponse_WhenMappingBookEntity_ShouldMapIdTitleAndReleaseYear()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity bookEntity = _bookEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
BookLiteResponse result = bookEntity.ToLiteResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(bookEntity.Id, result.Id);
|
||||
Assert.Equal(bookEntity.Title, result.Title);
|
||||
Assert.Equal(bookEntity.ReReleaseYear ?? bookEntity.OriginalReleaseYear, result.ReleaseYear);
|
||||
Assert.Null(result.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToLiteResponse_WhenBookHasNoReReleaseYear_ShouldFallBackToOriginalReleaseYear()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity bookEntity = _bookEntityFixture.Create();
|
||||
bookEntity.ReReleaseYear = null;
|
||||
|
||||
// Act
|
||||
BookLiteResponse result = bookEntity.ToLiteResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(bookEntity.OriginalReleaseYear, result.ReleaseYear);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToLiteResponses_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<BookLiteResponse> results = bookEntities.ToLiteResponses();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(bookEntities.Count, results.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToLiteResponses_WhenMappingPaginatedBookEntities_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
|
||||
PaginatedResultDto<BookEntity> paginatedBookEntities = _paginatedResultDtoFixture.Create(
|
||||
data: bookEntities,
|
||||
currentPage: 1,
|
||||
perPage: 10,
|
||||
count: 2,
|
||||
numberOfPages: 1);
|
||||
|
||||
// Act
|
||||
PaginatedResponse<BookLiteResponse> result = paginatedBookEntities.ToLiteResponses();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(paginatedBookEntities.Data.Count, result.Data.Count);
|
||||
Assert.Equal(paginatedBookEntities.CurrentPage, result.CurrentPage);
|
||||
Assert.Equal(paginatedBookEntities.PerPage, result.PerPage);
|
||||
Assert.Equal(paginatedBookEntities.Count, result.Count);
|
||||
Assert.Equal(paginatedBookEntities.NumberOfPages, result.NumberOfPages);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookLiteRowMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookLiteRowMappingTests
|
||||
{
|
||||
private readonly BookLiteRowFixture _bookLiteRowFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<BookLiteRow> _paginatedResultDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingBookLiteRow_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
BookLiteRow readModel = _bookLiteRowFixture.Create();
|
||||
|
||||
// Act
|
||||
BookLiteResponse result = readModel.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(readModel.Id, result.Id);
|
||||
Assert.Equal(readModel.Title, result.Title);
|
||||
Assert.Equal(readModel.ReleaseYear, result.ReleaseYear);
|
||||
Assert.Equal(readModel.CoverPath, result.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleBookLiteRows_ShouldMapAllCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<BookLiteRow> readModels = _bookLiteRowFixture.CreateMany(2);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<BookLiteResponse> results = readModels.ToResponses();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(readModels.Count, results.Count);
|
||||
Assert.Equal(readModels.Select(readModel => readModel.Id), results.Select(response => response.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingPaginatedBookLiteRows_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
List<BookLiteRow> readModels = _bookLiteRowFixture.CreateMany(2);
|
||||
PaginatedResultDto<BookLiteRow> paginatedReadModels = _paginatedResultDtoFixture.Create(
|
||||
data: readModels,
|
||||
currentPage: 1,
|
||||
perPage: 10,
|
||||
count: 2,
|
||||
numberOfPages: 1);
|
||||
|
||||
// Act
|
||||
PaginatedResponse<BookLiteResponse> result = paginatedReadModels.ToResponses();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(paginatedReadModels.Data.Count, result.Data.Count);
|
||||
Assert.Equal(paginatedReadModels.CurrentPage, result.CurrentPage);
|
||||
Assert.Equal(paginatedReadModels.PerPage, result.PerPage);
|
||||
Assert.Equal(paginatedReadModels.Count, result.Count);
|
||||
Assert.Equal(paginatedReadModels.NumberOfPages, result.NumberOfPages);
|
||||
}
|
||||
}
|
||||
+43
-7
@@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
@@ -21,14 +22,17 @@ public class GetBooksLiteRequestMappingTests
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetBooksLiteQuery result = request.ToQuery();
|
||||
GetBooksLiteQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(request.LibraryId, result.Filter.LibraryId);
|
||||
Assert.Equal(request.SearchTerm, result.Filter.SearchTerm);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.Equal(request.SearchTerm, result.SearchTerm);
|
||||
Assert.Equal(request.FilterAlphaKey, result.FilterAlphaKey);
|
||||
Assert.Equal(request.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
|
||||
Assert.Equal(request.SortBy, result.SortBy);
|
||||
Assert.Equal(request.SortOrder, result.SortOrder);
|
||||
Assert.NotNull(result.PaginationData);
|
||||
@@ -36,19 +40,49 @@ public class GetBooksLiteRequestMappingTests
|
||||
Assert.Equal(request.PerPage, result.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdIsNotParseable_ShouldMapItAsIs()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
string libraryId = "not-a-library-guid";
|
||||
|
||||
// Act
|
||||
GetBooksLiteQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdIsNull_ShouldMapNullLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetBooksLiteQuery result = request.ToQuery(null);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false);
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetBooksLiteQuery result = request.ToQuery();
|
||||
GetBooksLiteQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.PaginationData);
|
||||
Assert.Equal(request.LibraryId, result.Filter.LibraryId);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -56,9 +90,10 @@ public class GetBooksLiteRequestMappingTests
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(perPage: 25, includeCurrentPage: false);
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetBooksLiteQuery result = request.ToQuery();
|
||||
GetBooksLiteQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.PaginationData);
|
||||
@@ -71,9 +106,10 @@ public class GetBooksLiteRequestMappingTests
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(currentPage: 3, includePerPage: false);
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetBooksLiteQuery result = request.ToQuery();
|
||||
GetBooksLiteQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.PaginationData);
|
||||
|
||||
+41
-7
@@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
@@ -21,14 +22,15 @@ public class GetBooksRequestMappingTests
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetBooksQuery result = request.ToQuery();
|
||||
GetBooksQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(request.LibraryId, result.Filter.LibraryId);
|
||||
Assert.Equal(request.SearchTerm, result.Filter.SearchTerm);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.Equal(request.SearchTerm, result.SearchTerm);
|
||||
Assert.Equal(request.SortBy, result.SortBy);
|
||||
Assert.Equal(request.SortOrder, result.SortOrder);
|
||||
Assert.NotNull(result.PaginationData);
|
||||
@@ -36,19 +38,49 @@ public class GetBooksRequestMappingTests
|
||||
Assert.Equal(request.PerPage, result.PaginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdIsNotParseable_ShouldMapItAsIs()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
string libraryId = "not-a-library-guid";
|
||||
|
||||
// Act
|
||||
GetBooksQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdIsNull_ShouldMapNullLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetBooksQuery result = request.ToQuery(null);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create(includeCurrentPage: false, includePerPage: false);
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetBooksQuery result = request.ToQuery();
|
||||
GetBooksQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Null(result.PaginationData);
|
||||
Assert.Equal(request.LibraryId, result.Filter.LibraryId);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -56,9 +88,10 @@ public class GetBooksRequestMappingTests
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create(perPage: 25, includeCurrentPage: false);
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetBooksQuery result = request.ToQuery();
|
||||
GetBooksQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.PaginationData);
|
||||
@@ -71,9 +104,10 @@ public class GetBooksRequestMappingTests
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create(currentPage: 3, includePerPage: false);
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
GetBooksQuery result = request.ToQuery();
|
||||
GetBooksQuery result = request.ToQuery(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result.PaginationData);
|
||||
|
||||
+29
-21
@@ -52,6 +52,7 @@ public class GetBooksQueryHandlerTests
|
||||
{
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
@@ -75,12 +76,13 @@ public class GetBooksQueryHandlerTests
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
|
||||
PaginatedResultDto<BookEntity> paginatedBooks = _paginatedResultDtoFixture.Create(data: bookEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1);
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
_mockBookRepository.GetAllAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
shouldTrackEntities: false,
|
||||
cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedBooks));
|
||||
|
||||
// Act
|
||||
@@ -101,12 +103,13 @@ public class GetBooksQueryHandlerTests
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
||||
PaginatedResultDto<BookEntity> paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
_mockBookRepository.GetAllAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
shouldTrackEntities: false,
|
||||
cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedBooks));
|
||||
|
||||
// Act
|
||||
@@ -122,12 +125,13 @@ public class GetBooksQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
_mockBookRepository.GetAllAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
shouldTrackEntities: false,
|
||||
cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.FilterMustIncludeLibraryId);
|
||||
|
||||
// Act
|
||||
@@ -145,51 +149,55 @@ public class GetBooksQueryHandlerTests
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
PaginatedResultDto<BookEntity> paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
_mockBookRepository.GetAllAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
shouldTrackEntities: false,
|
||||
cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedBooks));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.Received(1).GetPaginatedAsync(
|
||||
await _mockBookRepository.Received(1).GetAllAsync(
|
||||
Arg.Is<PaginationDataDto>(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage &&
|
||||
paginationData.PerPage == query.PaginationData.PerPage),
|
||||
Arg.Is(query.SortBy),
|
||||
Arg.Is(query.SortOrder),
|
||||
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm),
|
||||
Arg.Is(cancellationToken));
|
||||
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) && filter.SearchTerm == query.SearchTerm),
|
||||
shouldTrackEntities: false,
|
||||
cancellationToken: Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid(), sortOrder: SortOrder.Ascending);
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid().ToString(), sortOrder: SortOrder.Ascending);
|
||||
PaginatedResultDto<BookEntity> paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
_mockBookRepository.GetAllAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
shouldTrackEntities: false,
|
||||
cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedBooks));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.Received(1).GetPaginatedAsync(
|
||||
await _mockBookRepository.Received(1).GetAllAsync(
|
||||
Arg.Is<PaginationDataDto?>(paginationData => paginationData == null),
|
||||
Arg.Is(query.SortBy),
|
||||
Arg.Is(query.SortOrder),
|
||||
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm),
|
||||
Arg.Any<CancellationToken>());
|
||||
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) && filter.SearchTerm == query.SearchTerm),
|
||||
shouldTrackEntities: false,
|
||||
cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -207,8 +215,8 @@ public class GetBooksQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.Filter.LibraryId), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == Guid.Parse(query.LibraryId!)), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetAllAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -225,7 +233,7 @@ public class GetBooksQueryHandlerTests
|
||||
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().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetAllAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -242,6 +250,6 @@ public class GetBooksQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetAllAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+53
-1
@@ -24,7 +24,59 @@ public class GetBooksQueryValidatorTests
|
||||
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: Guid.Empty);
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: string.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: " ");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsGuidEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: Guid.Empty.ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsNotAValidGuid_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: "not-a-library-guid");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
+38
-31
@@ -1,15 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
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;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
@@ -41,9 +41,9 @@ public class GetBooksLiteQueryHandlerTests
|
||||
private readonly IValidator<GetBooksLiteQuery> _mockValidator;
|
||||
private readonly GetBooksLiteQueryHandler _sut;
|
||||
private readonly Guid _userId;
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookLiteRowFixture _bookLiteRowFixture = new();
|
||||
private readonly GetBooksLiteQueryFixture _getBooksLiteQueryFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<BookEntity> _paginatedResultDtoFixture = new();
|
||||
private readonly PaginatedResultDtoFixture<BookLiteRow> _paginatedResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetBooksLiteQueryHandlerTests"/> class.
|
||||
@@ -52,6 +52,7 @@ public class GetBooksLiteQueryHandlerTests
|
||||
{
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
@@ -73,14 +74,14 @@ public class GetBooksLiteQueryHandlerTests
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<BookEntity> bookEntities = _bookEntityFixture.CreateMany(2);
|
||||
PaginatedResultDto<BookEntity> paginatedBooks = _paginatedResultDtoFixture.Create(data: bookEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1);
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
List<BookLiteRow> bookLiteRows = _bookLiteRowFixture.CreateMany(2);
|
||||
PaginatedResultDto<BookLiteRow> paginatedBooks = _paginatedResultDtoFixture.Create(data: bookLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1);
|
||||
_mockBookRepository.GetAllLiteAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedBooks));
|
||||
|
||||
// Act
|
||||
@@ -88,7 +89,7 @@ public class GetBooksLiteQueryHandlerTests
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(bookEntities.Count, result.Value.Data.Count);
|
||||
Assert.Equal(bookLiteRows.Count, result.Value.Data.Count);
|
||||
Assert.Equal(paginatedBooks.CurrentPage, result.Value.CurrentPage);
|
||||
Assert.Equal(paginatedBooks.PerPage, result.Value.PerPage);
|
||||
Assert.Equal(paginatedBooks.Count, result.Value.Count);
|
||||
@@ -100,13 +101,13 @@ public class GetBooksLiteQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||
PaginatedResultDto<BookEntity> paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
PaginatedResultDto<BookLiteRow> paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
|
||||
_mockBookRepository.GetAllLiteAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedBooks));
|
||||
|
||||
// Act
|
||||
@@ -122,12 +123,12 @@ public class GetBooksLiteQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
_mockBookRepository.GetAllLiteAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Library.FilterMustIncludeLibraryId);
|
||||
|
||||
// Act
|
||||
@@ -144,52 +145,58 @@ public class GetBooksLiteQueryHandlerTests
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
PaginatedResultDto<BookEntity> paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
PaginatedResultDto<BookLiteRow> paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
|
||||
_mockBookRepository.GetAllLiteAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedBooks));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.Received(1).GetPaginatedAsync(
|
||||
await _mockBookRepository.Received(1).GetAllLiteAsync(
|
||||
Arg.Is<PaginationDataDto>(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage &&
|
||||
paginationData.PerPage == query.PaginationData.PerPage),
|
||||
Arg.Is(query.SortBy),
|
||||
Arg.Is(query.SortOrder),
|
||||
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm),
|
||||
Arg.Is(cancellationToken));
|
||||
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) &&
|
||||
filter.SearchTerm == query.SearchTerm &&
|
||||
filter.FilterAlphaKey == query.FilterAlphaKey &&
|
||||
filter.ShouldIgnoreThePrefixForAlphaPicker == query.ShouldIgnoreThePrefixForAlphaPicker),
|
||||
cancellationToken: Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid(), sortOrder: SortOrder.Ascending);
|
||||
PaginatedResultDto<BookEntity> paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
|
||||
_mockBookRepository.GetPaginatedAsync(
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid().ToString(), sortOrder: SortOrder.Ascending);
|
||||
PaginatedResultDto<BookLiteRow> paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
|
||||
_mockBookRepository.GetAllLiteAsync(
|
||||
Arg.Any<PaginationDataDto?>(),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<SortOrder?>(),
|
||||
Arg.Any<LibraryFilterDto>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(paginatedBooks));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.Received(1).GetPaginatedAsync(
|
||||
await _mockBookRepository.Received(1).GetAllLiteAsync(
|
||||
Arg.Is<PaginationDataDto?>(paginationData => paginationData == null),
|
||||
Arg.Is(query.SortBy),
|
||||
Arg.Is(query.SortOrder),
|
||||
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm),
|
||||
Arg.Any<CancellationToken>());
|
||||
Arg.Is<LibraryFilterDto>(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) &&
|
||||
filter.SearchTerm == query.SearchTerm &&
|
||||
filter.FilterAlphaKey == query.FilterAlphaKey &&
|
||||
filter.ShouldIgnoreThePrefixForAlphaPicker == query.ShouldIgnoreThePrefixForAlphaPicker),
|
||||
cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -207,8 +214,8 @@ public class GetBooksLiteQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.Filter.LibraryId), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == Guid.Parse(query.LibraryId!)), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetAllLiteAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -225,7 +232,7 @@ public class GetBooksLiteQueryHandlerTests
|
||||
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().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetAllLiteAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -242,6 +249,6 @@ public class GetBooksLiteQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetAllLiteAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+53
-1
@@ -24,7 +24,59 @@ public class GetBooksLiteQueryValidatorTests
|
||||
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: Guid.Empty);
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: string.Empty);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: " ");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsGuidEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: Guid.Empty.ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsNotAValidGuid_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: "not-a-library-guid");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
+15
-3
@@ -32,7 +32,6 @@ public class GetBooksLiteRequestTests
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut);
|
||||
Assert.NotEqual(Guid.Empty, sut.LibraryId);
|
||||
Assert.True(sut.CurrentPage.HasValue);
|
||||
Assert.True(sut.PerPage.HasValue);
|
||||
}
|
||||
@@ -72,10 +71,9 @@ public class GetBooksLiteRequestTests
|
||||
GetBooksLiteRequest sut = _getBooksLiteRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
(Guid libraryId, int? currentPage, int? perPage, string? searchTerm, string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker, string? sortBy, SortOrder? sortOrder) = sut;
|
||||
(int? currentPage, int? perPage, string? searchTerm, string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker, string? sortBy, SortOrder? sortOrder) = sut;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(sut.LibraryId, libraryId);
|
||||
Assert.Equal(sut.CurrentPage, currentPage);
|
||||
Assert.Equal(sut.PerPage, perPage);
|
||||
Assert.Equal(sut.SearchTerm, searchTerm);
|
||||
@@ -84,4 +82,18 @@ public class GetBooksLiteRequestTests
|
||||
Assert.Equal(sut.SortBy, sortBy);
|
||||
Assert.Equal(sut.SortOrder, sortOrder);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest first = _getBooksLiteRequestFixture.Create();
|
||||
GetBooksLiteRequest second = first with { };
|
||||
|
||||
// Act
|
||||
bool areEqual = first == second;
|
||||
|
||||
// Assert
|
||||
Assert.True(areEqual);
|
||||
}
|
||||
}
|
||||
+15
-3
@@ -32,7 +32,6 @@ public class GetBooksRequestTests
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut);
|
||||
Assert.NotEqual(Guid.Empty, sut.LibraryId);
|
||||
Assert.True(sut.CurrentPage.HasValue);
|
||||
Assert.True(sut.PerPage.HasValue);
|
||||
}
|
||||
@@ -72,14 +71,27 @@ public class GetBooksRequestTests
|
||||
GetBooksRequest sut = _getBooksRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
(Guid libraryId, int? currentPage, int? perPage, string? searchTerm, string? sortBy, SortOrder? sortOrder) = sut;
|
||||
(int? currentPage, int? perPage, string? searchTerm, string? sortBy, SortOrder? sortOrder) = sut;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(sut.LibraryId, libraryId);
|
||||
Assert.Equal(sut.CurrentPage, currentPage);
|
||||
Assert.Equal(sut.PerPage, perPage);
|
||||
Assert.Equal(sut.SearchTerm, searchTerm);
|
||||
Assert.Equal(sut.SortBy, sortBy);
|
||||
Assert.Equal(sut.SortOrder, sortOrder);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest first = _getBooksRequestFixture.Create();
|
||||
GetBooksRequest second = first with { };
|
||||
|
||||
// Act
|
||||
bool areEqual = first == second;
|
||||
|
||||
// Assert
|
||||
Assert.True(areEqual);
|
||||
}
|
||||
}
|
||||
+270
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DTO.Filtering;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
@@ -1086,4 +1087,273 @@ public class BookRepositoryTests
|
||||
Assert.Equal(["The Art of War", "Beneath the Surface"], result.Value.Data.Select(book => book.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedLiteRows()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
List<BookEntity> books = _bookEntityFixture.CreateMany(3);
|
||||
foreach (BookEntity book in books)
|
||||
book.LibraryId = libraryId;
|
||||
_mockContext.Books.AddRange(books);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count);
|
||||
Assert.Equal(3, result.Value.Data.Count);
|
||||
Assert.Equal(1, result.Value.CurrentPage);
|
||||
Assert.Equal(10, result.Value.PerPage);
|
||||
Assert.Equal(1, result.Value.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
BaseFilterDto filter = _baseFilterDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenPaginationDataIsNull_ShouldReturnAllLiteRows()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
List<BookEntity> books = _bookEntityFixture.CreateMany(3);
|
||||
foreach (BookEntity book in books)
|
||||
book.LibraryId = libraryId;
|
||||
_mockContext.Books.AddRange(books);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(3, result.Value.Count);
|
||||
Assert.Equal(3, result.Value.Data.Count);
|
||||
Assert.Equal(1, result.Value.CurrentPage);
|
||||
Assert.Equal(3, result.Value.PerPage);
|
||||
Assert.Equal(1, result.Value.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingLiteRows()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity fellowshipBook = _bookEntityFixture.Create();
|
||||
fellowshipBook.LibraryId = libraryId;
|
||||
fellowshipBook.Title = "The Fellowship of the Ring";
|
||||
BookEntity towersBook = _bookEntityFixture.Create();
|
||||
towersBook.LibraryId = libraryId;
|
||||
towersBook.Title = "The Two Towers";
|
||||
_mockContext.Books.AddRange(fellowshipBook, towersBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Fellowship");
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookLiteRow row = Assert.Single(result.Value.Data);
|
||||
Assert.Equal("The Fellowship of the Ring", row.Title);
|
||||
Assert.Equal(1, result.Value.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenPageSizeSmallerThanBookCount_ShouldReturnCorrectPageMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
List<BookEntity> books = _bookEntityFixture.CreateMany(5);
|
||||
foreach (BookEntity book in books)
|
||||
book.LibraryId = libraryId;
|
||||
_mockContext.Books.AddRange(books);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 2, perPage: 2);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(5, result.Value.Count);
|
||||
Assert.Equal(3, result.Value.NumberOfPages);
|
||||
Assert.Equal(2, result.Value.CurrentPage);
|
||||
Assert.Equal(2, result.Value.PerPage);
|
||||
Assert.Equal(2, result.Value.Data.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenSortByTitleDescending_ShouldReturnLiteRowsInDescendingOrder()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity bookA = _bookEntityFixture.Create();
|
||||
bookA.LibraryId = libraryId;
|
||||
bookA.Title = "Book A";
|
||||
BookEntity bookB = _bookEntityFixture.Create();
|
||||
bookB.LibraryId = libraryId;
|
||||
bookB.Title = "Book B";
|
||||
_mockContext.Books.AddRange(bookA, bookB);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(paginationData, "title", SortOrder.Descending, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(["Book B", "Book A"], result.Value.Data.Select(row => row.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity beneathBook = _bookEntityFixture.Create(title: "Beneath the Surface", includeMetadata: false);
|
||||
beneathBook.LibraryId = libraryId;
|
||||
BookEntity artOfWarBook = _bookEntityFixture.Create(title: "The Art of War", includeMetadata: false);
|
||||
artOfWarBook.LibraryId = libraryId;
|
||||
_mockContext.Books.AddRange(beneathBook, artOfWarBook);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: true);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// Without stripping the prefix, "The Art of War" would be sorted after "Beneath the Surface", since its sort key would start with "the" instead of "art".
|
||||
Assert.Equal(["The Art of War", "Beneath the Surface"], result.Value.Data.Select(row => row.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenBookHasReReleaseYear_ShouldProjectReReleaseYearAsReleaseYear()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookLiteRow row = Assert.Single(result.Value.Data);
|
||||
Assert.Equal(book.ReReleaseYear, row.ReleaseYear);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenBookHasNoReReleaseYear_ShouldProjectOriginalReleaseYearAsReleaseYear()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
book.ReReleaseYear = null;
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookLiteRow row = Assert.Single(result.Value.Data);
|
||||
Assert.Equal(book.OriginalReleaseYear, row.ReleaseYear);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenBookHasCoverArtwork_ShouldProjectTheCoverFileName()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, fileName: "cover.jpg")];
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookLiteRow row = Assert.Single(result.Value.Data);
|
||||
Assert.Equal("cover.jpg", row.CoverPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllLiteAsync_WhenBookHasNoCoverArtwork_ShouldProjectNullCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
book.BookArtwork = [];
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
Result<PaginatedResultDto<BookLiteRow>> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
BookLiteRow row = Assert.Single(result.Value.Data);
|
||||
Assert.Null(row.CoverPath);
|
||||
}
|
||||
}
|
||||
+53
-13
@@ -19,6 +19,7 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks;
|
||||
@@ -63,12 +64,12 @@ public class GetBooksEndpointTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Book.NotFound", "The requested book was not found.");
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBooksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
@@ -77,19 +78,18 @@ public class GetBooksEndpointTests
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
|
||||
Assert.Equal("Book.NotFound", problemDetails.ProblemDetails.Title);
|
||||
Assert.Equal("The requested book was not found.", problemDetails.ProblemDetails.Detail);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
|
||||
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
@@ -118,18 +118,20 @@ public class GetBooksEndpointTests
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetBooksQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBooksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(Arg.Is<GetBooksQuery>(query =>
|
||||
query.Filter.LibraryId == request.LibraryId &&
|
||||
query.Filter.SearchTerm == request.SearchTerm &&
|
||||
query.LibraryId == libraryId.ToString() &&
|
||||
query.SearchTerm == request.SearchTerm &&
|
||||
query.SortBy == request.SortBy &&
|
||||
query.SortOrder == request.SortOrder &&
|
||||
query.PaginationData != null &&
|
||||
@@ -138,6 +140,44 @@ public class GetBooksEndpointTests
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBooksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetBooksQuery>(query => query.LibraryId == "not-a-library-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksRequest request = _getBooksRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBooksQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture)));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetBooksQuery>(query => query.LibraryId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
|
||||
+55
-13
@@ -19,6 +19,7 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite;
|
||||
@@ -63,12 +64,12 @@ public class GetBooksLiteEndpointTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Book.NotFound", "The requested book was not found.");
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBooksLiteQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
@@ -77,19 +78,18 @@ public class GetBooksLiteEndpointTests
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
|
||||
Assert.Equal("Book.NotFound", problemDetails.ProblemDetails.Title);
|
||||
Assert.Equal("The requested book was not found.", problemDetails.ProblemDetails.Detail);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
|
||||
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
@@ -118,18 +118,22 @@ public class GetBooksLiteEndpointTests
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetBooksLiteQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBooksLiteQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePaginatedResponse(bookCount: 0)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(Arg.Is<GetBooksLiteQuery>(query =>
|
||||
query.Filter.LibraryId == request.LibraryId &&
|
||||
query.Filter.SearchTerm == request.SearchTerm &&
|
||||
query.LibraryId == libraryId.ToString() &&
|
||||
query.SearchTerm == request.SearchTerm &&
|
||||
query.FilterAlphaKey == request.FilterAlphaKey &&
|
||||
query.ShouldIgnoreThePrefixForAlphaPicker == request.ShouldIgnoreThePrefixForAlphaPicker &&
|
||||
query.SortBy == request.SortBy &&
|
||||
query.SortOrder == request.SortOrder &&
|
||||
query.PaginationData != null &&
|
||||
@@ -138,6 +142,44 @@ public class GetBooksLiteEndpointTests
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBooksLiteQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePaginatedResponse(bookCount: 0)));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetBooksLiteQuery>(query => query.LibraryId == "not-a-library-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetBooksLiteQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePaginatedResponse(bookCount: 0)));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetBooksLiteQuery>(query => query.LibraryId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user