Refactors the book, artist, and album slices across the stack

This commit is contained in:
BinaryAlley committed 2026-09-17 13:30:48 -07:00
1 parent 8aaf9fe64e
commit ea6eb9f796
439 files changed
+28235 -3156

No files matched your search

@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
@@ -11,14 +11,13 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Converters;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
@@ -33,6 +32,7 @@ using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -48,12 +48,8 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true,
Converters = {
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase),
new BookJsonConverter()
}
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly AddBookRequestFixture _requestBookFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
@@ -106,62 +102,62 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
// Assert
response.EnsureSuccessStatusCode();
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
BookResponse? bookResponse = await response.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.NotNull(bookResponse);
// metadata checks
Assert.Equal(bookRequest.Metadata!.Title, bookResponse!.Metadata.Title);
Assert.Equal(bookRequest.Metadata.OriginalTitle, bookResponse.Metadata.OriginalTitle.Value);
Assert.Equal(bookRequest.Metadata.Description, bookResponse.Metadata.Description.Value);
Assert.Equal(bookRequest.Metadata.Publisher, bookResponse.Metadata.Publisher.Value);
Assert.Equal(bookRequest.Metadata.PageCount, bookResponse.Metadata.PageCount.Value);
Assert.Equal(bookRequest.Metadata.OriginalTitle, bookResponse.Metadata.OriginalTitle);
Assert.Equal(bookRequest.Metadata.Description, bookResponse.Metadata.Description);
Assert.Equal(bookRequest.Metadata.Publisher, bookResponse.Metadata.Publisher);
Assert.Equal(bookRequest.Metadata.PageCount, bookResponse.Metadata.PageCount);
Assert.Equal(bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate, bookResponse.Metadata.ReleaseInfo.OriginalReleaseDate.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear, bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseDate, bookResponse.Metadata.ReleaseInfo.ReReleaseDate.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseYear, bookResponse.Metadata.ReleaseInfo.ReReleaseYear.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo!.ReleaseCountry, bookResponse.Metadata.ReleaseInfo.ReleaseCountry.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseVersion, bookResponse.Metadata.ReleaseInfo.ReleaseVersion.Value);
Assert.Equal(bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate, bookResponse.Metadata.ReleaseInfo!.OriginalReleaseDate);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear, bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseDate, bookResponse.Metadata.ReleaseInfo.ReReleaseDate);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseYear, bookResponse.Metadata.ReleaseInfo.ReReleaseYear);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseCountry, bookResponse.Metadata.ReleaseInfo.ReleaseCountry);
Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseVersion, bookResponse.Metadata.ReleaseInfo.ReleaseVersion);
// language checks
Assert.Equal(bookRequest.Metadata.Language!.LanguageCode, bookResponse.Metadata.Language.Value.LanguageCode);
Assert.Equal(bookRequest.Metadata.Language.LanguageName, bookResponse.Metadata.Language.Value.LanguageName);
Assert.Equal(bookRequest.Metadata.Language.NativeName, bookResponse.Metadata.Language.Value.NativeName.Value);
Assert.Equal(bookRequest.Metadata.Language!.LanguageCode, bookResponse.Metadata.Language!.LanguageCode);
Assert.Equal(bookRequest.Metadata.Language.LanguageName, bookResponse.Metadata.Language.LanguageName);
Assert.Equal(bookRequest.Metadata.Language.NativeName, bookResponse.Metadata.Language.NativeName);
// original language checks
Assert.Equal(bookRequest.Metadata.OriginalLanguage!.LanguageCode, bookResponse.Metadata.OriginalLanguage.Value.LanguageCode);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.LanguageName, bookResponse.Metadata.OriginalLanguage.Value.LanguageName);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.NativeName, bookResponse.Metadata.OriginalLanguage.Value.NativeName.Value);
Assert.Equal(bookRequest.Metadata.OriginalLanguage!.LanguageCode, bookResponse.Metadata.OriginalLanguage!.LanguageCode);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.LanguageName, bookResponse.Metadata.OriginalLanguage.LanguageName);
Assert.Equal(bookRequest.Metadata.OriginalLanguage.NativeName, bookResponse.Metadata.OriginalLanguage.NativeName);
// genres checks
Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres.Count);
Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres!.Count);
Assert.Equal(
bookRequest.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x),
bookResponse.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x));
// tags checks
Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags.Count);
Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags!.Count);
Assert.Equal(
bookRequest.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x),
bookResponse.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x));
// book specific properties
Assert.Equal(bookRequest.Format, bookResponse.Format.Value);
Assert.Equal(bookRequest.Edition, bookResponse.Edition.Value);
Assert.Equal(bookRequest.VolumeNumber, bookResponse.VolumeNumber.Value);
Assert.Equal(bookRequest.ASIN, bookResponse.ASIN.Value);
Assert.Equal(bookRequest.GoodreadsId, bookResponse.GoodreadsId.Value);
Assert.Equal(bookRequest.LCCN, bookResponse.LCCN.Value);
Assert.Equal(bookRequest.OCLCNumber, bookResponse.OCLCNumber.Value);
Assert.Equal(bookRequest.OpenLibraryId, bookResponse.OpenLibraryId.Value);
Assert.Equal(bookRequest.LibraryThingId, bookResponse.LibraryThingId.Value);
Assert.Equal(bookRequest.GoogleBooksId, bookResponse.GoogleBooksId.Value);
Assert.Equal(bookRequest.BarnesAndNobleId, bookResponse.BarnesAndNobleId.Value);
Assert.Equal(bookRequest.AppleBooksId, bookResponse.AppleBooksId.Value);
Assert.Equal(bookRequest.Format, bookResponse.Format);
Assert.Equal(bookRequest.Edition, bookResponse.Edition);
Assert.Equal(bookRequest.VolumeNumber, bookResponse.VolumeNumber);
Assert.Equal(bookRequest.ASIN, bookResponse.ASIN);
Assert.Equal(bookRequest.GoodreadsId, bookResponse.GoodreadsId);
Assert.Equal(bookRequest.LCCN, bookResponse.LCCN);
Assert.Equal(bookRequest.OCLCNumber, bookResponse.OCLCNumber);
Assert.Equal(bookRequest.OpenLibraryId, bookResponse.OpenLibraryId);
Assert.Equal(bookRequest.LibraryThingId, bookResponse.LibraryThingId);
Assert.Equal(bookRequest.GoogleBooksId, bookResponse.GoogleBooksId);
Assert.Equal(bookRequest.BarnesAndNobleId, bookResponse.BarnesAndNobleId);
Assert.Equal(bookRequest.AppleBooksId, bookResponse.AppleBooksId);
// ISBNs checks
Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs.Count);
Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs!.Count);
var requestIsbnData = bookRequest.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList();
var responseIsbnData = bookResponse.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList();
Assert.Equal(requestIsbnData.Count, responseIsbnData.Count);
@@ -172,9 +168,9 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
}
// ratings checks
Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings.Count);
Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings!.Count);
var requestRatingData = bookRequest.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList();
var responseRatingData = bookResponse.Ratings.Select(r => new { Source = r.Source.Value, r.Value, r.MaxValue, VoteCount = r.VoteCount.Value }).OrderBy(x => x.Source).ToList();
var responseRatingData = bookResponse.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList();
Assert.Equal(requestRatingData.Count, responseRatingData.Count);
for (int i = 0; i < requestRatingData.Count; i++)
{
@@ -186,18 +182,18 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
// series checks
if (bookRequest.Series is not null)
Assert.Equal(bookRequest.Series.Title, bookResponse.Series.Value.Metadata.Title);
Assert.Equal(bookRequest.Series.Title, bookResponse.Series!.Title);
else
Assert.Null(bookResponse.Series.Value);
Assert.Null(bookResponse.Series);
// check Location header
Assert.NotNull(response.Headers.Location);
string locationUri = response.Headers.Location!.ToString();
Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id.Value}", locationUri);
Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id}", locationUri);
// extract ID from Location header and compare
string idFromHeader = locationUri.Split('/').Last();
Assert.Equal(idFromHeader, bookResponse!.Id.ToString());
Assert.Equal(idFromHeader, bookResponse.Id.ToString());
}
[Fact]
@@ -1119,7 +1115,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
HttpResponseMessage response = await PostBookAsync(bookRequest);
// Assert
await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.ContributorsListCannotBeNull.Description);
await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorsListCannotBeNull.Description);
}
[Fact]
@@ -1235,15 +1231,15 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
BookResponse? bookResponse = await response.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
Assert.NotNull(bookResponse);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<BookContributorEntity> links = [.. dbContext.Books
.Include(book => book.BookContributors)
.Single(book => book.Id == bookResponse!.Id.Value)
.BookContributors];
.Include(book => book.Contributors)
.Single(book => book.Id == bookResponse!.Id)
.Contributors];
Assert.Equal(2, links.Count);
Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId));
Assert.Contains(links, link => link.Role == MediaContributorRole.Author);
@@ -1754,6 +1750,51 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task AddBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _requestBookFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task AddBook_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []);
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", bookRequest, cts.Token)
);
Assert.Null(exception);
}
[Fact]
public async Task AddBook_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
{
// Arrange
AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []);
using CancellationTokenSource cts = new();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", bookRequest, cts.Token);
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
/// Posts a request to add a book to the media library owned by the authenticated user of the current test.
/// </summary>
@@ -1821,7 +1862,7 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
{
HttpResponseMessage response = await PostBookAsync(bookRequest);
response.EnsureSuccessStatusCode();
Book? bookResponse = await response.Content.ReadFromJsonAsync<Book>(_jsonOptions);
BookResponse? bookResponse = await response.Content.ReadFromJsonAsync<BookResponse>(_jsonOptions);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.NotNull(bookResponse);
}
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -36,6 +37,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingAvailabilityEndpointTests"/> class.
@@ -63,7 +65,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/availability");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
// Assert
response.EnsureSuccessStatusCode();
@@ -79,7 +81,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
public async Task GetReadingAvailability_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/availability");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/availability");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -91,6 +93,57 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingAvailability_WhenBookBelongsToAnotherUser_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingAvailability_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/availability");
// Assert
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
// reported as not found, without disclosing that the book exists in another library.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingAvailability_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/availability");
// Assert
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
// validation errors instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetReadingAvailability_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
@@ -98,7 +151,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/availability");
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/availability");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
@@ -123,6 +176,20 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<AuthenticatedLu
return (libraryId, bookId);
}
/// <summary>
/// Seeds a user that is not the authenticated one and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
@@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
@@ -52,7 +53,7 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
public async Task GetReadingManifest_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/manifest");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/manifest");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -66,13 +67,35 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid bookId = await SeedBookAsync(otherUserId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/manifest");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingManifest_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/manifest");
// Assert
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
// reported as not found, without disclosing that the book exists in another library.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
}
[Fact]
@@ -80,10 +103,10 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
{
// Arrange
Guid userId = GetCurrentUserId();
Guid bookId = await SeedBookAsync(userId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/manifest");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
// Assert
string content = await response.Content.ReadAsStringAsync();
@@ -98,18 +121,33 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/manifest");
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/manifest");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task GetReadingManifest_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/manifest");
// Assert
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
// validation errors instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/> and an EPUB book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded book.</returns>
private async Task<Guid> SeedBookAsync(Guid userId)
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -120,7 +158,7 @@ public class GetReadingManifestEndpointTests : IClassFixture<AuthenticatedLumina
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return bookId;
return (libraryId, bookId);
}
/// <summary>
@@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
@@ -52,7 +53,7 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
public async Task GetReadingResource_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/cover");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/cover");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -66,13 +67,35 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid bookId = await SeedBookAsync(otherUserId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/resources/cover");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/cover");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingResource_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/resources/cover");
// Assert
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
// reported as not found, without disclosing that the book exists in another library.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
}
[Fact]
@@ -80,10 +103,10 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
{
// Arrange
Guid userId = GetCurrentUserId();
Guid bookId = await SeedBookAsync(userId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/resources/cover");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/cover");
// Assert
string content = await response.Content.ReadAsStringAsync();
@@ -98,18 +121,33 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/cover");
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/cover");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task GetReadingResource_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/resources/cover");
// Assert
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
// validation errors instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/> and an EPUB book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded book.</returns>
private async Task<Guid> SeedBookAsync(Guid userId)
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -120,7 +158,7 @@ public class GetReadingResourceEndpointTests : IClassFixture<AuthenticatedLumina
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return bookId;
return (libraryId, bookId);
}
/// <summary>
@@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
@@ -52,7 +53,7 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
public async Task GetReadingSection_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/chapter-1");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/chapter-1");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -66,13 +67,35 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid bookId = await SeedBookAsync(otherUserId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/sections/chapter-1");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/chapter-1");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
}
[Fact]
public async Task GetReadingSection_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}/reading/sections/chapter-1");
// Assert
// The route library id is enforced, so a book can never be read through another library's route, and the mismatch is
// reported as not found, without disclosing that the book exists in another library.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("BookNotFound", content, StringComparison.Ordinal);
}
[Fact]
@@ -80,10 +103,10 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
{
// Arrange
Guid userId = GetCurrentUserId();
Guid bookId = await SeedBookAsync(userId);
(Guid libraryId, Guid bookId) = await SeedBookAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}/reading/sections/chapter-1");
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/chapter-1");
// Assert
string content = await response.Content.ReadAsStringAsync();
@@ -98,18 +121,33 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/chapter-1");
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/chapter-1");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task GetReadingSection_WhenRouteIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/books/not-a-guid/reading/sections/chapter-1");
// Assert
// The route values are kept as raw strings, so the unparseable Ids reach the query validator, which reports clean
// validation errors instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/> and an EPUB book belonging to it.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded book.</returns>
private async Task<Guid> SeedBookAsync(Guid userId)
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -120,7 +158,7 @@ public class GetReadingSectionEndpointTests : IClassFixture<AuthenticatedLuminaA
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return bookId;
return (libraryId, bookId);
}
/// <summary>
@@ -1,4 +1,4 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
@@ -35,6 +35,7 @@ using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -134,9 +135,9 @@ public class UpdateBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<BookContributorEntity> links = dbContext.Books
.Include(book => book.BookContributors)
.Include(book => book.Contributors)
.Single(book => book.Id == bookId)
.BookContributors
.Contributors
.ToList();
Assert.Equal(2, links.Count);
Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId));
@@ -1792,6 +1793,40 @@ public class UpdateBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task UpdateBook_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title");
UpdateBookRequest request = _requestBookFixture.Create();
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request, cts.Token)
);
Assert.Null(exception);
}
[Fact]
public async Task UpdateBook_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title");
UpdateBookRequest request = _requestBookFixture.Create();
using CancellationTokenSource cts = new();
// Act & Assert
Exception? exception = await Record.ExceptionAsync(async () =>
{
cts.Cancel();
await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request, cts.Token);
});
Assert.IsType<TaskCanceledException>(exception);
}
/// <summary>
/// Updates the book described by the provided request, seeding the media library, the book and the referenced media contributors.
/// </summary>
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
@@ -63,19 +64,19 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookWithCoverAsync(userId, "/media/books/old-cover.jpg");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
string storedPath = JsonSerializer.Deserialize<string>(content)!;
string storedPath = JsonSerializer.Deserialize<UpdateBookCoverResponse>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!.CoverPath;
Assert.False(string.IsNullOrWhiteSpace(storedPath));
Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookArtworkEntity coverArtwork = dbContext.Books
.SelectMany(book => book.BookArtwork)
.SelectMany(book => book.Artwork)
.Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover);
Assert.Equal(storedPath, coverArtwork.FileName);
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
@@ -86,21 +87,21 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId);
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
string storedPath = JsonSerializer.Deserialize<string>(content)!;
string storedPath = JsonSerializer.Deserialize<UpdateBookCoverResponse>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!.CoverPath;
Assert.False(string.IsNullOrWhiteSpace(storedPath));
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookArtworkEntity coverArtwork = dbContext.Books
.SelectMany(book => book.BookArtwork)
.SelectMany(book => book.Artwork)
.Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover);
Assert.Equal(storedPath, coverArtwork.FileName);
}
@@ -109,7 +110,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
public async Task UpdateBookCover_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
{
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@@ -123,7 +124,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
public async Task UpdateBookCover_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/not-a-guid/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/not-a-guid/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
@@ -138,10 +139,10 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId);
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/books/{bookId}/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
@@ -151,6 +152,25 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
}
[Fact]
public async Task UpdateBookCover_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookId) = await SeedLibraryAndBookAsync(userId);
Guid otherLibraryId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{otherLibraryId}/books/{bookId}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
}
[Fact]
public async Task UpdateBookCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
@@ -158,12 +178,78 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
HttpResponseMessage response = await unauthenticatedClient.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/cover", CreateCoverForm("cover.png"));
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task UpdateBookCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithBookCoverCannotBeNull()
{
// Arrange
MultipartFormDataContent form = [];
form.Add(new StringContent("unrelated-field"), "unrelated-field");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("BookCoverCannotBeNull", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task UpdateBookCover_WhenUploadedFileIsNotAnImage_ShouldReturnUnprocessableEntityWithCoverFileMustBeAnImage()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
MultipartFormDataContent form = CreateCoverForm([1, 2, 3, 4, 5, 6, 7, 8], "cover.png");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("CoverFileMustBeAnImage", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task UpdateBookCover_WhenUploadedFileIsTooLarge_ShouldReturnUnprocessableEntityWithFileTooLarge()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
// The artwork size limit is 10 MiB, so the payload exceeds it by one byte.
byte[] payload = new byte[(10 * 1024 * 1024) + 1];
payload[0] = 137;
payload[1] = 80;
payload[2] = 78;
payload[3] = 71;
payload[4] = 13;
payload[5] = 10;
payload[6] = 26;
payload[7] = 10;
MultipartFormDataContent form = CreateCoverForm(payload, "cover.png");
// Act
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("FileTooLarge", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a multipart form carrying a minimal PNG-like payload.
/// </summary>
@@ -181,6 +267,17 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
payload[5] = 10;
payload[6] = 26;
payload[7] = 10;
return CreateCoverForm(payload, fileName);
}
/// <summary>
/// Creates a multipart form carrying the provided payload as an uploaded file.
/// </summary>
/// <param name="payload">The bytes of the uploaded file.</param>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
private static MultipartFormDataContent CreateCoverForm(byte[] payload, string fileName)
{
MultipartFormDataContent form = [];
ByteArrayContent fileContent = new(payload);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
@@ -203,7 +300,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture<AuthenticatedLuminaApi
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false);
BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: bookId, artworkType: ArtworkType.Cover, fileName: existingCoverFileName, status: ArtworkStatus.Enriched);
book.BookArtwork.Add(existingCover);
book.Artwork.Add(existingCover);
dbContext.Libraries.Add(library);
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();