mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 01:11:10 +00:00
Adds independent metadata and artwork enrichment
Splits the single combined enrichment phase of the media library scan into independent, modular jobs, so that the metadata and the artwork of a book are enriched separately and only when their respective triggers fire. - Adds the MediaContributorRoleCategory enum (Other first, then Author, Translator, Illustrator, Publisher and Narrator) and makes the role category canonical, so that roles describing the same kind of contribution are never treated as distinct. - Realizes the media contributor bounded context: a MediaContributor is a person, unique by display name, without a role. The role moves to the per-work participation (BookContributors), so that a single contributor can play multiple roles. Contributors are created and linked by the metadata enrichment job, and exposed to subsequent jobs. - Makes the Book aggregate pure: the enrichment tracking state (metadata status, providers, timestamps and covers) no longer lives on the domain aggregate, but stays in the Books table, managed directly by the jobs. - Models artwork generically as a BookArtwork child table (type, ordinal, content hash, status and provider), so that each piece of artwork is tracked independently and a change of one does not require the others to be re-fetched. - Splits the scan DAG into ResultsSave, ProviderConfigurationInvalidation, MetadataEnrichment and ArtworkEnrichment jobs. The invalidation job fingerprints the provider configuration of a library and resets the enrichment state of the affected channel when it changed. The artwork job resolves the missing artwork, hashing it to detect identical covers and skip re-copying. Content-changed books are reset by the results save job. - Deletes the book and its stored artwork when the file disappears from the library. - Adds the migration creating the new tables, backfilling the existing covers into the artwork table, and adding the configuration fingerprints. - Localizes the new scan job stages, and fixes the invalidation job wiping the library content locations by persisting the fingerprints through the change tracker instead of the repository update action.
This commit is contained in:
1 parent
4ee2976806
commit
565fe68239
98 files changed
+5845
-630
No files matched your search
+2
-1
@@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
@@ -101,7 +102,7 @@ public class AddBookRequestMappingTests
|
||||
[
|
||||
new(
|
||||
_mediaContributorNameDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe"),
|
||||
_mediaContributorRoleDtoFixture.Create(name: "Author", category: "Writing")
|
||||
_mediaContributorRoleDtoFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author)
|
||||
)
|
||||
],
|
||||
ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)],
|
||||
|
||||
+4
-8
@@ -7,7 +7,6 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
@@ -24,7 +23,7 @@ public class BookMetadataDtoMappingTests
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItAndMarkTheBookAsEnriched()
|
||||
public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItToTheBook()
|
||||
{
|
||||
// Arrange
|
||||
Book book = _bookFixture.Create();
|
||||
@@ -37,7 +36,7 @@ public class BookMetadataDtoMappingTests
|
||||
pageCount: 398);
|
||||
|
||||
// Act
|
||||
Result<Success> result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow);
|
||||
Result<Success> result = book.ApplyMetadata(metadata);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
@@ -46,9 +45,6 @@ public class BookMetadataDtoMappingTests
|
||||
Assert.Equal("The first part of J.R.R. Tolkien's epic adventure.", book.Metadata.Description.Value);
|
||||
Assert.Equal(BookFormat.Paperback, book.Format.Value);
|
||||
Assert.Equal("Houghton Mifflin", book.Metadata.Publisher.Value);
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal("Goodreads", book.MetadataProvider.Value);
|
||||
Assert.True(book.LastMetadataUpdateUtc.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -64,10 +60,10 @@ public class BookMetadataDtoMappingTests
|
||||
};
|
||||
|
||||
// Act
|
||||
Result<Success> result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow);
|
||||
Result<Success> result = book.ApplyMetadata(metadata);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(MetadataStatus.Pending, book.MetadataStatus);
|
||||
Assert.NotEqual("The Fellowship of the Ring", book.Metadata.Title);
|
||||
}
|
||||
}
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryMediaItemDeletedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryMediaItemDeletedDomainEventHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IBookArtworkService _mockBookArtworkService;
|
||||
private readonly ILogger<LibraryMediaItemDeletedDomainEventHandler> _mockLogger;
|
||||
private readonly LibraryMediaItemDeletedDomainEventHandler _sut;
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryMediaItemDeletedDomainEventHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryMediaItemDeletedDomainEventHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
|
||||
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
_mockLogger = Substitute.For<ILogger<LibraryMediaItemDeletedDomainEventHandler>>();
|
||||
|
||||
_sut = new LibraryMediaItemDeletedDomainEventHandler(_mockUnitOfWork, _mockBookArtworkService, _mockLogger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenBookExistsAtPath_ShouldDeleteTheBookAndItsArtwork()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
|
||||
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Result.Deleted);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
LibraryMediaItemDeletedDomainEvent domainEvent = new(
|
||||
Guid.NewGuid(),
|
||||
libraryId,
|
||||
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
|
||||
book.Path,
|
||||
DateTime.UtcNow);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId.Value, book.Id, "My Library", "Frank Herbert", book.Title);
|
||||
await _mockBookRepository.Received(1).DeleteAsync(book.Id, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenNoBookExistsAtPath_ShouldDoNothing()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(null));
|
||||
|
||||
LibraryMediaItemDeletedDomainEvent domainEvent = new(
|
||||
Guid.NewGuid(),
|
||||
libraryId,
|
||||
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
|
||||
"/books/deleted.epub",
|
||||
DateTime.UtcNow);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
|
||||
await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
|
||||
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork"));
|
||||
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
LibraryMediaItemDeletedDomainEvent domainEvent = new(
|
||||
Guid.NewGuid(),
|
||||
libraryId,
|
||||
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
|
||||
book.Path,
|
||||
DateTime.UtcNow);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// a failing artwork deletion must not prevent the book from being removed, so the deletion is only logged
|
||||
await _mockBookRepository.Received(1).DeleteAsync(book.Id, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenGetBookFails_ShouldThrowEventualConsistencyException()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
Error error = Error.Failure("Database.Error", "Failed to get the book");
|
||||
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
LibraryMediaItemDeletedDomainEvent domainEvent = new(
|
||||
Guid.NewGuid(),
|
||||
libraryId,
|
||||
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
|
||||
"/books/deleted.epub",
|
||||
DateTime.UtcNow);
|
||||
|
||||
// Act
|
||||
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
|
||||
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(error, exception.EventualConsistencyError);
|
||||
await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenDeleteBookFails_ShouldThrowEventualConsistencyException()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
|
||||
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Result.Deleted);
|
||||
Error error = Error.Failure("Database.Error", "Failed to delete the book");
|
||||
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
LibraryMediaItemDeletedDomainEvent domainEvent = new(
|
||||
Guid.NewGuid(),
|
||||
libraryId,
|
||||
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
|
||||
book.Path,
|
||||
DateTime.UtcNow);
|
||||
|
||||
// Act
|
||||
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
|
||||
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(error, exception.EventualConsistencyError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
-14
@@ -1765,20 +1765,6 @@ public class AddBookCommandValidatorTests
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithInvalidLengthContributorRoleCategory_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
AddBookCommand bookCommand = _commandBookFixture.Create();
|
||||
bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = new Faker().Random.String2(51) } } : contributor)] };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError()
|
||||
{
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
@@ -23,7 +24,7 @@ public class MediaContributorDtoTests
|
||||
// Arrange
|
||||
MediaContributorDto expected = new(
|
||||
new MediaContributorNameDto("John Smith", "Johnathan Smith"),
|
||||
new MediaContributorRoleDto("Author", "Writer")
|
||||
new MediaContributorRoleDto("Author", MediaContributorRoleCategory.Author)
|
||||
);
|
||||
|
||||
// Act
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
@@ -21,7 +22,7 @@ public class MediaContributorRoleDtoTests
|
||||
public void RoundTrip_WhenSerializingRole_ShouldPreserveValues()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorRoleDto expected = new("Author", "Writer");
|
||||
MediaContributorRoleDto expected = new("Author", MediaContributorRoleCategory.Author);
|
||||
|
||||
// Act
|
||||
string json = JsonSerializer.Serialize(expected, _jsonOptions);
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -53,7 +54,7 @@ public class BookMetadataDtoTests
|
||||
"1234567890",
|
||||
"id12345",
|
||||
[new IsbnDto("978-0-306-40615-7", IsbnFormat.Isbn13)],
|
||||
[new MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), new MediaContributorRoleDto("Author", "Writer"))],
|
||||
[new MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), new MediaContributorRoleDto("Author", MediaContributorRoleCategory.Author))],
|
||||
[new BookRatingDto(4.5m, 5m, BookRatingSource.Goodreads, 1000)],
|
||||
"https://example.com/dune.jpg"
|
||||
);
|
||||
|
||||
+236
@@ -1,10 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
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.Pagination;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Filtering;
|
||||
using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
@@ -14,6 +16,9 @@ using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
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 Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System;
|
||||
@@ -39,6 +44,9 @@ public class BookRepositoryTests
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly IsbnEntityFixture _isbnEntityFixture = new();
|
||||
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
|
||||
private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new();
|
||||
private readonly BaseFilterDtoFixture _baseFilterDtoFixture = new();
|
||||
@@ -528,4 +536,232 @@ public class BookRepositoryTests
|
||||
Assert.Single(retrievedBook.Ratings);
|
||||
Assert.Equal(4.5M, retrievedBook.Ratings.First().Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksNeedingArtworkAsync_WhenCalled_ShouldReturnOnlyBooksWithoutAnEnrichedCover()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity bookWithoutCover = _bookEntityFixture.Create();
|
||||
bookWithoutCover.LibraryId = libraryId;
|
||||
bookWithoutCover.Path = "/books/a.epub";
|
||||
bookWithoutCover.BookArtwork = [];
|
||||
BookEntity bookWithEnrichedCover = _bookEntityFixture.Create();
|
||||
bookWithEnrichedCover.LibraryId = libraryId;
|
||||
bookWithEnrichedCover.Path = "/books/b.epub";
|
||||
bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
BookEntity bookWithFailedCover = _bookEntityFixture.Create();
|
||||
bookWithFailedCover.LibraryId = libraryId;
|
||||
bookWithFailedCover.Path = "/books/c.epub";
|
||||
bookWithFailedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithFailedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Failed)];
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.BookArtwork = [];
|
||||
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<BookEntity>> result = await _sut.GetBooksNeedingArtworkAsync(libraryId, null, 10, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, book => book.Id == bookWithoutCover.Id);
|
||||
Assert.Contains(result.Value, book => book.Id == bookWithFailedCover.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBooksNeedingArtworkCountAsync_WhenCalled_ShouldCountOnlyBooksWithoutAnEnrichedCover()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity bookWithoutCover = _bookEntityFixture.Create();
|
||||
bookWithoutCover.LibraryId = libraryId;
|
||||
bookWithoutCover.BookArtwork = [];
|
||||
BookEntity bookWithEnrichedCover = _bookEntityFixture.Create();
|
||||
bookWithEnrichedCover.LibraryId = libraryId;
|
||||
bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.BookArtwork = [];
|
||||
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<int> result = await _sut.GetBooksNeedingArtworkCountAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(1, result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths()
|
||||
{
|
||||
// Arrange
|
||||
// the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity changedBook = _bookEntityFixture.Create();
|
||||
changedBook.LibraryId = libraryId;
|
||||
changedBook.Path = "/books/changed.epub";
|
||||
changedBook.MetadataStatus = MetadataStatus.Enriched;
|
||||
changedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
BookEntity unchangedBook = _bookEntityFixture.Create();
|
||||
unchangedBook.LibraryId = libraryId;
|
||||
unchangedBook.Path = "/books/unchanged.epub";
|
||||
unchangedBook.MetadataStatus = MetadataStatus.Enriched;
|
||||
unchangedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
context.Books.AddRange(changedBook, unchangedBook);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.ResetEnrichmentStateForPathsAsync(libraryId, ["/books/changed.epub"], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.BookArtwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id);
|
||||
Assert.NotNull(resetBook);
|
||||
Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus);
|
||||
Assert.Equal(ArtworkStatus.Pending, resetBook.BookArtwork.Single().Status);
|
||||
BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == unchangedBook.Id);
|
||||
Assert.NotNull(keptBook);
|
||||
Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResetMetadataStatusForLibraryAsync_WhenCalled_ShouldResetTheMetadataStatusOfAllBooksOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
// the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity enrichedBook = _bookEntityFixture.Create();
|
||||
enrichedBook.LibraryId = libraryId;
|
||||
enrichedBook.MetadataStatus = MetadataStatus.Enriched;
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Enriched;
|
||||
context.Books.AddRange(enrichedBook, bookOfAnotherLibrary);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.ResetMetadataStatusForLibraryAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
BookEntity? resetBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == enrichedBook.Id);
|
||||
Assert.NotNull(resetBook);
|
||||
Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus);
|
||||
BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == bookOfAnotherLibrary.Id);
|
||||
Assert.NotNull(keptBook);
|
||||
Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResetArtworkStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkStatusOfTheLibraryBooks()
|
||||
{
|
||||
// Arrange
|
||||
// the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used
|
||||
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
|
||||
anchorConnection.Open();
|
||||
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
|
||||
context.Database.EnsureCreated();
|
||||
BookRepository sut = new(context);
|
||||
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
book.LibraryId = libraryId;
|
||||
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
|
||||
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
|
||||
bookOfAnotherLibrary.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
|
||||
context.Books.AddRange(book, bookOfAnotherLibrary);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await sut.ResetArtworkStatusForLibraryAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
BookArtworkEntity? resetArtwork = await context.Set<BookArtworkEntity>().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == book.Id);
|
||||
Assert.NotNull(resetArtwork);
|
||||
Assert.Equal(ArtworkStatus.Pending, resetArtwork!.Status);
|
||||
BookArtworkEntity? keptArtwork = await context.Set<BookArtworkEntity>().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == bookOfAnotherLibrary.Id);
|
||||
Assert.NotNull(keptArtwork);
|
||||
Assert.Equal(ArtworkStatus.Enriched, keptArtwork!.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenCalled_ShouldReturnTheAuthorDisplayNames()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity firstBook = _bookEntityFixture.Create();
|
||||
BookEntity secondBook = _bookEntityFixture.Create();
|
||||
BookEntity bookWithoutAuthor = _bookEntityFixture.Create();
|
||||
_mockContext.Books.AddRange(firstBook, secondBook, bookWithoutAuthor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
MediaContributorEntity translator = _mediaContributorEntityFixture.Create(displayName: "Jane Translator");
|
||||
_mockContext.MediaContributors.AddRange(author, translator);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
_mockContext.BookContributors.AddRange(
|
||||
_bookContributorEntityFixture.Create(bookId: firstBook.Id, mediaContributorId: author.Id, roleName: "Author", roleCategory: MediaContributorRoleCategory.Author),
|
||||
_bookContributorEntityFixture.Create(bookId: secondBook.Id, mediaContributorId: translator.Id, roleName: "Translator", roleCategory: MediaContributorRoleCategory.Translator));
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyDictionary<Guid, string?>> result = await _sut.GetAuthorsDisplayNamesByBookIdsAsync([firstBook.Id, secondBook.Id, bookWithoutAuthor.Id], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// only the author contributor of the first book is returned; the book with no author is not included
|
||||
Assert.Single(result.Value);
|
||||
Assert.Equal("Frank Herbert", result.Value[firstBook.Id]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAsync_WhenBookExists_ShouldRemoveItAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create();
|
||||
_mockContext.Books.Add(book);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAsync(book.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
EntityEntry<BookEntity>? deletedBook = _mockContext.ChangeTracker.Entries<BookEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Deleted && entityEntry.Entity.Id == book.Id);
|
||||
Assert.NotNull(deletedBook);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAsync_WhenBookDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.DataAccess.Core.Repositories.MediaContributors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaContributorRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly MediaContributorRepository _sut;
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaContributorRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public MediaContributorRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new MediaContributorRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindOrCreateByDisplayNameAsync_WhenContributorExists_ShouldReturnTheExistingContributor()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Stephen King");
|
||||
_mockContext.MediaContributors.Add(existingContributor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync("stephen king", null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
// the comparison is case-insensitive, so the existing contributor is returned and no new one is created
|
||||
Assert.Equal(existingContributor.Id, result.Value.Id);
|
||||
Assert.Equal("Stephen King", result.Value.DisplayName);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindOrCreateByDisplayNameAsync_WhenContributorDoesNotExist_ShouldCreateAndAddANewContributor()
|
||||
{
|
||||
// Arrange
|
||||
string displayName = "Frank Herbert";
|
||||
|
||||
// Act
|
||||
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync(displayName, "Franklin Patrick Herbert", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(displayName, result.Value.DisplayName);
|
||||
Assert.Equal("Franklin Patrick Herbert", result.Value.LegalName);
|
||||
|
||||
EntityEntry<MediaContributorEntity>? addedContributor = _mockContext.ChangeTracker.Entries<MediaContributorEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == result.Value.Id);
|
||||
Assert.NotNull(addedContributor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindOrCreateByDisplayNameAsync_WhenContributorWithSameNameExistsInDifferentCase_ShouldNotCreateADuplicate()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
_mockContext.MediaContributors.Add(existingContributor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync("FRANK HERBERT", "Franklin Patrick Herbert", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(existingContributor.Id, result.Value.Id);
|
||||
Assert.Equal(existingContributor.DisplayName, result.Value.DisplayName);
|
||||
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheContributorsWithTheProvidedIds()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create();
|
||||
MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create();
|
||||
MediaContributorEntity thirdContributor = _mediaContributorEntityFixture.Create();
|
||||
_mockContext.MediaContributors.AddRange(firstContributor, secondContributor, thirdContributor);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<MediaContributorEntity>> result = await _sut.GetByIdsAsync([firstContributor.Id, thirdContributor.Id], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Contains(result.Value, contributor => contributor.Id == firstContributor.Id);
|
||||
Assert.Contains(result.Value, contributor => contributor.Id == thirdContributor.Id);
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ public class LuminaDbContextTests : IDisposable
|
||||
|
||||
// Assert
|
||||
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
|
||||
Assert.Equal(25, tableNames.Length);
|
||||
Assert.Equal(28, tableNames.Length);
|
||||
Assert.Contains("Books", tableNames);
|
||||
Assert.Contains("Users", tableNames);
|
||||
Assert.Contains("UserSettings", tableNames);
|
||||
@@ -73,6 +73,9 @@ public class LuminaDbContextTests : IDisposable
|
||||
Assert.Contains("BookRatings", tableNames);
|
||||
Assert.Contains("BookISBNs", tableNames);
|
||||
Assert.Contains("Themes", tableNames);
|
||||
Assert.Contains("MediaContributors", tableNames);
|
||||
Assert.Contains("BookContributors", tableNames);
|
||||
Assert.Contains("BookArtwork", tableNames);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+33
-10
@@ -2,6 +2,7 @@
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -17,7 +18,7 @@ public class MediaContributorTests
|
||||
{
|
||||
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
|
||||
private readonly MediaContributorNameFixture _mediaContributorNameFixture = new();
|
||||
private readonly MediaContributorRoleFixture _mediaContributorRoleFixture = new();
|
||||
private readonly MediaContributorFixture _mediaContributorFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithPreExistingIdAndValues_ShouldCreateContributor()
|
||||
@@ -25,22 +26,22 @@ public class MediaContributorTests
|
||||
// Arrange
|
||||
MediaContributorId id = _mediaContributorIdFixture.Create();
|
||||
MediaContributorName name = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional<string>.Some("Jane Doe Smith"));
|
||||
MediaContributorRole role = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew");
|
||||
Optional<string> biography = Optional<string>.Some("A well-known author.");
|
||||
Optional<DateOnly> dateOfBirth = Optional<DateOnly>.Some(new DateOnly(1980, 1, 1));
|
||||
Optional<DateOnly> dateOfDeath = Optional<DateOnly>.None();
|
||||
|
||||
// Act
|
||||
Result<MediaContributor> result = MediaContributor.Create(id, name, role, dateOfBirth, dateOfDeath);
|
||||
Result<MediaContributor> result = MediaContributor.Create(id, name, biography, dateOfBirth, dateOfDeath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(id, result.Value.Id);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.Equal(role, result.Value.Role);
|
||||
Assert.True(result.Value.Biography.HasValue);
|
||||
Assert.Equal("A well-known author.", result.Value.Biography.Value);
|
||||
Assert.True(result.Value.DateOfBirth.HasValue);
|
||||
Assert.Equal(new DateOnly(1980, 1, 1), result.Value.DateOfBirth.Value);
|
||||
Assert.False(result.Value.DateOfDeath.HasValue);
|
||||
Assert.False(result.Value.Biography.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -48,24 +49,46 @@ public class MediaContributorTests
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorName name = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional<string>.None());
|
||||
MediaContributorRole role = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew");
|
||||
|
||||
// Act
|
||||
Result<MediaContributor> result = MediaContributor.Create(_mediaContributorIdFixture.Create(), name, role, Optional<DateOnly>.None(), Optional<DateOnly>.None());
|
||||
Result<MediaContributor> result = MediaContributor.Create(_mediaContributorIdFixture.Create(), name, Optional<string>.None(), Optional<DateOnly>.None(), Optional<DateOnly>.None());
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.Biography.HasValue);
|
||||
Assert.False(result.Value.DateOfBirth.HasValue);
|
||||
Assert.False(result.Value.DateOfDeath.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithoutId_ShouldThrowNotImplementedException()
|
||||
public void Create_WhenCalledWithoutId_ShouldCreateContributorWithGeneratedId()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorName name = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional<string>.None());
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<NotImplementedException>(() => MediaContributor.Create(name));
|
||||
// Act
|
||||
Result<MediaContributor> result = MediaContributor.Create(name);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(result.Value.Id);
|
||||
Assert.Equal(name, result.Value.Name);
|
||||
Assert.False(result.Value.Biography.HasValue);
|
||||
Assert.False(result.Value.DateOfBirth.HasValue);
|
||||
Assert.False(result.Value.DateOfDeath.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithPreExistingId_ShouldNotContainARole()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributor contributor = _mediaContributorFixture.Create();
|
||||
|
||||
// Act
|
||||
Type contributorType = contributor.GetType();
|
||||
|
||||
// Assert
|
||||
// the contributor is a person, agnostic of the roles it played in the media items, so it must not expose a role
|
||||
Assert.Null(contributorType.GetProperty("Role"));
|
||||
}
|
||||
}
|
||||
+26
-11
@@ -1,6 +1,9 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
@@ -15,22 +18,34 @@ public class MediaContributorRoleTests
|
||||
private readonly MediaContributorRoleFixture _mediaContributorRoleFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithNameAndCategory_ShouldCreateRole()
|
||||
public void Create_WhenCalledWithDisplayNameAndCategory_ShouldCreateRole()
|
||||
{
|
||||
// Act
|
||||
MediaContributorRole role = MediaContributorRole.Create("Actor", "Crew");
|
||||
Result<MediaContributorRole> result = MediaContributorRole.Create("Author", MediaContributorRoleCategory.Author);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Actor", role.Name);
|
||||
Assert.Equal("Crew", role.Category);
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Author", result.Value.DisplayName);
|
||||
Assert.Equal(MediaContributorRoleCategory.Author, result.Value.Category);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithEmptyDisplayName_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<MediaContributorRole> result = MediaContributorRole.Create(" ", MediaContributorRoleCategory.Author);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.MediaContributors.MediaContributorRoleNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew");
|
||||
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew");
|
||||
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
|
||||
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
|
||||
|
||||
// Act
|
||||
bool result = firstRole.Equals(secondRole);
|
||||
@@ -40,11 +55,11 @@ public class MediaContributorRoleTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithDifferentName_ShouldReturnFalse()
|
||||
public void Equals_WithDifferentDisplayName_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew");
|
||||
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Director", category: "Crew");
|
||||
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
|
||||
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Writer", category: MediaContributorRoleCategory.Author);
|
||||
|
||||
// Act
|
||||
bool result = firstRole.Equals(secondRole);
|
||||
@@ -57,8 +72,8 @@ public class MediaContributorRoleTests
|
||||
public void Equals_WithDifferentCategory_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew");
|
||||
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Voice");
|
||||
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author);
|
||||
MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Translator);
|
||||
|
||||
// Act
|
||||
bool result = firstRole.Equals(secondRole);
|
||||
|
||||
+44
-14
@@ -1,8 +1,11 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
@@ -15,46 +18,73 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoun
|
||||
public class BookTests
|
||||
{
|
||||
private readonly BookFixture _bookFixture = new();
|
||||
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalledWithValidData_ShouldCreateBookWithPendingMetadataStatus()
|
||||
public void Create_WhenCalledWithValidData_ShouldCreateBook()
|
||||
{
|
||||
// Act
|
||||
Book book = _bookFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(book);
|
||||
Assert.Equal(MetadataStatus.Pending, book.MetadataStatus);
|
||||
Assert.False(book.LastMetadataUpdateUtc.HasValue);
|
||||
Assert.False(book.MetadataProvider.HasValue);
|
||||
Assert.NotNull(book.Metadata);
|
||||
Assert.NotNull(book.Path);
|
||||
Assert.NotNull(book.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MarkMetadataAsEnriched_WhenCalled_ShouldUpdateStatusAndProvider()
|
||||
public void UpdateContributors_WhenCalled_ShouldReplaceTheContributors()
|
||||
{
|
||||
// Arrange
|
||||
Book book = _bookFixture.Create();
|
||||
DateTime lastUpdateUtc = DateTime.UtcNow;
|
||||
MediaContributorId firstContributorId = _mediaContributorIdFixture.Create();
|
||||
MediaContributorId secondContributorId = _mediaContributorIdFixture.Create();
|
||||
|
||||
// Act
|
||||
book.MarkMetadataAsEnriched("Goodreads", lastUpdateUtc);
|
||||
book.UpdateContributors([firstContributorId, secondContributorId]);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal("Goodreads", book.MetadataProvider.Value);
|
||||
Assert.Equal(lastUpdateUtc, book.LastMetadataUpdateUtc.Value);
|
||||
Assert.Equal(2, book.Contributors.Count);
|
||||
Assert.Contains(book.Contributors, contributorId => contributorId == firstContributorId);
|
||||
Assert.Contains(book.Contributors, contributorId => contributorId == secondContributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MarkMetadataAsFailed_WhenCalled_ShouldUpdateStatus()
|
||||
public void UpdateContributors_WhenCalledAgain_ShouldReplaceTheContributors()
|
||||
{
|
||||
// Arrange
|
||||
Book book = _bookFixture.Create();
|
||||
book.UpdateContributors([_mediaContributorIdFixture.Create()]);
|
||||
MediaContributorId replacementContributorId = _mediaContributorIdFixture.Create();
|
||||
|
||||
// Act
|
||||
book.MarkMetadataAsFailed();
|
||||
book.UpdateContributors([replacementContributorId]);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MetadataStatus.Failed, book.MetadataStatus);
|
||||
// the previous contributors are replaced, not appended
|
||||
MediaContributorId contributorId = Assert.Single(book.Contributors);
|
||||
Assert.Equal(replacementContributorId, contributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_WhenCalled_ShouldNotExposeEnrichmentTracking()
|
||||
{
|
||||
// Arrange
|
||||
Book book = _bookFixture.Create();
|
||||
Type bookType = book.GetType();
|
||||
|
||||
// Act
|
||||
bool hasMetadataStatus = bookType.GetProperty("MetadataStatus") is not null;
|
||||
bool hasLastMetadataUpdateUtc = bookType.GetProperty("LastMetadataUpdateUtc") is not null;
|
||||
bool hasMetadataProvider = bookType.GetProperty("MetadataProvider") is not null;
|
||||
bool hasCoverImagePath = bookType.GetProperty("CoverImagePath") is not null;
|
||||
|
||||
// Assert
|
||||
// the enrichment state is a persistence concern, tracked on the repository entity by the enrichment jobs
|
||||
Assert.False(hasMetadataStatus);
|
||||
Assert.False(hasLastMetadataUpdateUtc);
|
||||
Assert.False(hasMetadataProvider);
|
||||
Assert.False(hasCoverImagePath);
|
||||
}
|
||||
}
|
||||
+17
-4
@@ -40,7 +40,7 @@ public class BookLibraryTypeScannerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobChainWithMetadataEnrichment()
|
||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobChainWithEnrichmentJobs()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
@@ -48,7 +48,9 @@ public class BookLibraryTypeScannerTests
|
||||
TestScanJob diffJob = CreateJob<IMediaLibraryScanDiffJob>();
|
||||
TestScanJob hashJob = CreateJob<IMediaLibraryScanHashJob>();
|
||||
TestScanJob saveJob = CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
TestScanJob invalidationJob = CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
TestScanJob enrichmentJob = CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
TestScanJob artworkEnrichmentJob = CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
BookLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
@@ -63,9 +65,14 @@ public class BookLibraryTypeScannerTests
|
||||
Assert.Contains(diffJob, hashJob.Parents);
|
||||
Assert.Contains(saveJob, hashJob.Children);
|
||||
Assert.Contains(hashJob, saveJob.Parents);
|
||||
Assert.Contains(enrichmentJob, saveJob.Children);
|
||||
Assert.Contains(saveJob, enrichmentJob.Parents);
|
||||
Assert.Contains(invalidationJob, saveJob.Children);
|
||||
Assert.Contains(saveJob, invalidationJob.Parents);
|
||||
Assert.Contains(enrichmentJob, invalidationJob.Children);
|
||||
Assert.Contains(invalidationJob, enrichmentJob.Parents);
|
||||
Assert.Contains(artworkEnrichmentJob, enrichmentJob.Children);
|
||||
Assert.Contains(enrichmentJob, artworkEnrichmentJob.Parents);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -77,7 +84,9 @@ public class BookLibraryTypeScannerTests
|
||||
CreateJob<IMediaLibraryScanDiffJob>();
|
||||
CreateJob<IMediaLibraryScanHashJob>();
|
||||
CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
BookLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
@@ -88,7 +97,9 @@ public class BookLibraryTypeScannerTests
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanDiffJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanHashJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanResultsSaveJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
private TestScanJob CreateJob<TJob>() where TJob : class, IMediaLibraryScanJob
|
||||
@@ -111,7 +122,9 @@ public class BookLibraryTypeScannerTests
|
||||
IMediaLibraryScanDiffJob,
|
||||
IMediaLibraryScanHashJob,
|
||||
IMediaLibraryScanResultsSaveJob,
|
||||
IMediaLibraryScanMetadataEnrichmentJob
|
||||
IMediaLibraryScanProviderConfigurationInvalidationJob,
|
||||
IMediaLibraryScanMetadataEnrichmentJob,
|
||||
IMediaLibraryScanArtworkEnrichmentJob
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
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.Plugins;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanArtworkEnrichmentJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanArtworkEnrichmentJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<MediaLibraryScanArtworkEnrichmentJob> _mockLogger;
|
||||
private readonly MediaLibraryScanArtworkEnrichmentJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanArtworkEnrichmentJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanArtworkEnrichmentJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_mockLogger = Substitute.For<ILogger<MediaLibraryScanArtworkEnrichmentJob>>();
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory, _mockLogger)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndTrackTheCoverArtworkAsEnriched()
|
||||
{
|
||||
// Arrange
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul);
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title");
|
||||
SetupSingleBookPage(book, artworkPluginId);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await mockBookArtworkService.Received(1).SaveBookArtworkAsync(
|
||||
_libraryId.Value,
|
||||
book.Id,
|
||||
"My Library",
|
||||
"Frank Herbert",
|
||||
"Test Title",
|
||||
Arg.Any<ArtworkDto>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork);
|
||||
Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType);
|
||||
Assert.Equal(0, coverArtwork.Ordinal);
|
||||
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
|
||||
Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName);
|
||||
Assert.Equal(123ul, coverArtwork.ContentHash);
|
||||
Assert.Equal("Artwork Provider", coverArtwork.Provider);
|
||||
Assert.NotNull(coverArtwork.LastUpdateUtc);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenResolvedArtworkIsIdenticalToTheStoredOne_ShouldKeepTheStoredArtworkAndMarkItAsEnriched()
|
||||
{
|
||||
// Arrange
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul);
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
// the book already has a stored cover with the same content hash as the resolved artwork
|
||||
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))];
|
||||
SetupSingleBookPage(book, artworkPluginId);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the identical artwork is not copied again, so the artwork storage service is not called and the stored file name is kept
|
||||
await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork);
|
||||
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
|
||||
Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName);
|
||||
Assert.Equal("Artwork Provider", coverArtwork.Provider);
|
||||
Assert.NotNull(coverArtwork.LastUpdateUtc);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoProviderReturnsArtwork_ShouldMarkTheCoverArtworkAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((ArtworkDto?)null);
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, artworkPluginId);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork);
|
||||
Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType);
|
||||
Assert.Equal(0, coverArtwork.Ordinal);
|
||||
Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status);
|
||||
Assert.Null(coverArtwork.FileName);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichmentWithoutMarkingBooksAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// a library without artwork providers must not mark its books as failed to resolve, so the books are not even queried
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wires a real service provider with the given artwork provider and services, so that the job resolves them from the dependency injection container.
|
||||
/// </summary>
|
||||
/// <param name="artworkPluginId">The Id of the plugin providing the artwork.</param>
|
||||
/// <param name="artworkProvider">The artwork provider to resolve.</param>
|
||||
/// <param name="bookArtworkService">The service used to store the artwork of the books.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork.</param>
|
||||
private void SetupRealServiceProvider(Guid artworkPluginId, IArtworkProvider artworkProvider, IBookArtworkService bookArtworkService, IFileHashService fileHashService)
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
services.AddSingleton(bookArtworkService);
|
||||
services.AddSingleton(fileHashService);
|
||||
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
|
||||
ServiceProvider realServiceProvider = services.BuildServiceProvider();
|
||||
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the repositories so that the job processes a single page containing the given book, configured with the given artwork provider.
|
||||
/// </summary>
|
||||
/// <param name="book">The book whose artwork the job must resolve.</param>
|
||||
/// <param name="artworkPluginId">The Id of the plugin configured as artwork provider for the library.</param>
|
||||
private void SetupSingleBookPage(BookEntity book, Guid artworkPluginId)
|
||||
{
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)
|
||||
]));
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
}
|
||||
}
|
||||
+122
-165
@@ -1,21 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
@@ -27,6 +31,7 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContex
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
@@ -55,6 +60,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IMediaContributorRepository _mockMediaContributorRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<MediaLibraryScanMetadataEnrichmentJob> _mockLogger;
|
||||
private readonly MediaLibraryScanMetadataEnrichmentJob _sut;
|
||||
@@ -62,11 +68,11 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
@@ -86,8 +92,10 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
@@ -125,7 +133,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -145,8 +153,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -285,116 +292,125 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the enrichment state is tracked directly on the entity, so the failed status is visible on the same instance
|
||||
Assert.Equal(MetadataStatus.Failed, book.MetadataStatus);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMetadataIsEnriched_ShouldSetTheEnrichmentTrackingColumnsOnTheEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the enrichment tracking columns are managed directly on the entity by the enrichment job
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal("First Provider", book.MetadataProvider);
|
||||
Assert.NotNull(book.LastMetadataUpdateUtc);
|
||||
Assert.Equal("First Title", book.Title);
|
||||
Assert.Equal("First Publisher", book.Publisher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMetadataHasContributors_ShouldFindOrCreateThemAndLinkThemToTheBook()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author);
|
||||
MediaContributorDto translator = _mediaContributorDtoFixture.Create(displayName: "Jane Translator", roleName: "Translator", roleCategory: MediaContributorRoleCategory.Translator);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author, translator]));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
MediaContributorEntity translatorEntity = _mediaContributorEntityFixture.Create(displayName: "Jane Translator");
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(authorEntity));
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(translatorEntity));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
|
||||
// the participation rows are replaced on the entity, carrying the role and the category of each contributor
|
||||
Assert.Equal(2, book.BookContributors.Count);
|
||||
BookContributorEntity linkedAuthor = Assert.Single(book.BookContributors, contributor => contributor.MediaContributorId == authorEntity.Id);
|
||||
Assert.Equal("Author", linkedAuthor.RoleName);
|
||||
Assert.Equal(MediaContributorRoleCategory.Author, linkedAuthor.RoleCategory);
|
||||
Assert.Equal(book.Id, linkedAuthor.BookId);
|
||||
BookContributorEntity linkedTranslator = Assert.Single(book.BookContributors, contributor => contributor.MediaContributorId == translatorEntity.Id);
|
||||
Assert.Equal("Translator", linkedTranslator.RoleName);
|
||||
Assert.Equal(MediaContributorRoleCategory.Translator, linkedTranslator.RoleCategory);
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheSameContributorAppearsInMultipleBooksOfAPage_ShouldFindOrCreateItOnlyOnce()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author]));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
|
||||
BookEntity firstBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/a.epub");
|
||||
BookEntity secondBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/b.epub");
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([
|
||||
_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)
|
||||
]));
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)]));
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
.Returns(Result.From(2));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([firstBook, secondBook]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<BookEntity>(entity => entity.MetadataStatus == MetadataStatus.Failed),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtworkConfigurationRepositoryReturnsFailure_ShouldStillEnrichTheMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure(description: "Failed to get the artwork provider configurations"));
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
|
||||
MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(authorEntity));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockBookRepository.Received(1).UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndSetTheBookCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
|
||||
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(firstPluginId, firstProvider);
|
||||
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
services.AddSingleton(mockBookArtworkService);
|
||||
using ServiceProvider realServiceProvider = services.BuildServiceProvider();
|
||||
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
|
||||
|
||||
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
|
||||
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await mockBookArtworkService.Received(1).SaveBookArtworkAsync(
|
||||
_libraryId.Value,
|
||||
book.Id,
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
"First Title",
|
||||
Arg.Any<ArtworkDto>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<BookEntity>(entity => entity.CoverImagePath == "\\media\\books\\Library\\Author\\Title\\cover.jpeg"),
|
||||
Arg.Any<CancellationToken>());
|
||||
// the contributor cache of the page guarantees a single contributor per person, so the repository is queried only once
|
||||
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
Assert.Single(firstBook.BookContributors);
|
||||
Assert.Single(secondBook.BookContributors);
|
||||
Assert.Equal(authorEntity.Id, firstBook.BookContributors[0].MediaContributorId);
|
||||
Assert.Equal(authorEntity.Id, secondBook.BookContributors[0].MediaContributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -472,63 +488,6 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseArtworkProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
Guid localPluginId = Guid.NewGuid();
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IMetadataProvider localProvider = Substitute.For<IMetadataProvider>();
|
||||
localProvider.Name.Returns("Local Provider");
|
||||
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
localProvider.RequiresWebAccess.Returns(false);
|
||||
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Local Title"));
|
||||
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Web Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.RequiresWebAccess.Returns(true);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(localPluginId, localProvider);
|
||||
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
|
||||
using ServiceProvider realServiceProvider = services.BuildServiceProvider();
|
||||
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
|
||||
|
||||
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, localPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the artwork provider requiring access to the web is skipped when the library does not permit downloading data from the web
|
||||
await artworkProvider.DidNotReceive().GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container.
|
||||
/// </summary>
|
||||
@@ -570,8 +529,6 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
}
|
||||
}
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanProviderConfigurationInvalidationJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository;
|
||||
private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<MediaLibraryScanProviderConfigurationInvalidationJob> _mockLogger;
|
||||
private readonly MediaLibraryScanProviderConfigurationInvalidationJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _metadataConfigurationEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanProviderConfigurationInvalidationJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanProviderConfigurationInvalidationJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository);
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_mockLogger = Substitute.For<ILogger<MediaLibraryScanProviderConfigurationInvalidationJob>>();
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanProviderConfigurationInvalidationJob(_mockServiceScopeFactory, _mockLogger)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoFingerprintIsStored_ShouldSeedTheFingerprintsWithoutResettingAnything()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: null);
|
||||
SetupLibraryAndConfigurations(library);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// a missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted
|
||||
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMetadataFingerprintDiffers_ShouldResetTheMetadataStatus()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE", artworkProvidersConfigurationFingerprint: null);
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job
|
||||
await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtworkFingerprintDiffers_ShouldResetTheArtworkStatus()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: "STALE");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job
|
||||
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFingerprintsMatch_ShouldNotResetAnythingButStillPersistTheFingerprints()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
|
||||
List<LibraryMetadataProviderConfigurationEntity> metadataConfigurations = _metadataConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1);
|
||||
List<LibraryArtworkProviderConfigurationEntity> artworkConfigurations = _artworkConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1);
|
||||
SetupLibraryAndConfigurations(library, metadataConfigurations, artworkConfigurations);
|
||||
|
||||
// the stored fingerprints match the ones computed from the current provider configuration
|
||||
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(metadataConfigurations, false, library.CanDownloadMetadataFromWeb);
|
||||
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, library.CanDownloadMetadataFromWeb);
|
||||
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
|
||||
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted
|
||||
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBothFingerprintsDiffer_ShouldPersistTheUpdatedFingerprintsViaSaveChangesOnly()
|
||||
{
|
||||
// Arrange
|
||||
// both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: "STALE_ARTWORK");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and
|
||||
// flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run
|
||||
await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the media library"));
|
||||
SetupConfigurations();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the repositories so that the job reads the provided library and its provider configurations.
|
||||
/// </summary>
|
||||
/// <param name="library">The media library the job must read.</param>
|
||||
/// <param name="metadataConfigurations">The metadata provider configurations of the media library.</param>
|
||||
/// <param name="artworkConfigurations">The artwork provider configurations of the media library.</param>
|
||||
private void SetupLibraryAndConfigurations(LibraryEntity library, List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
|
||||
{
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
SetupConfigurations(metadataConfigurations, artworkConfigurations);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the provider configuration repositories and the user settings repository used by the job.
|
||||
/// </summary>
|
||||
/// <param name="metadataConfigurations">The metadata provider configurations of the media library, if already created by the caller.</param>
|
||||
/// <param name="artworkConfigurations">The artwork provider configurations of the media library, if already created by the caller.</param>
|
||||
private void SetupConfigurations(List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
|
||||
{
|
||||
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>(
|
||||
metadataConfigurations ?? [
|
||||
_metadataConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1),
|
||||
_metadataConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2)
|
||||
]));
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(
|
||||
artworkConfigurations ?? [
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1),
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2)
|
||||
]));
|
||||
|
||||
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
}
|
||||
}
|
||||
+34
@@ -21,6 +21,7 @@ using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -38,6 +39,7 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryScanSnapshotRepository _mockSnapshotRepository;
|
||||
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MediaLibraryScanResultsSaveJob _sut;
|
||||
@@ -62,8 +64,10 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockSnapshotRepository = Substitute.For<ILibraryScanSnapshotRepository>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockSnapshotRepository);
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
@@ -89,6 +93,10 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["deleted.pdf"]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["changed.pdf"]));
|
||||
_mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
@@ -105,18 +113,44 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryMediaItemDeletedDomainEvent>(domainEvent => domainEvent.Path == "deleted.pdf"), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Is<IReadOnlyCollection<string>>(paths => paths.Any(path => path == "changed.pdf")), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book1.pdf" && book.Title == "book1" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book2.pdf" && book.Title == "book2" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoContentChanged_ShouldNotResetTheEnrichmentState()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// no book content changed since the last scan, so the enrichment state of the books must not be reset
|
||||
await _mockBookRepository.DidNotReceive().ResetEnrichmentStateForPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookAlreadyExists_ShouldSkipInsertingIt()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
using Lumina.Plugins.Calibre.Core.Mapping;
|
||||
using Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
|
||||
@@ -210,32 +211,32 @@ public class CalibreMapperTests
|
||||
MediaContributorDto author = result.Contributors[0];
|
||||
Assert.Equal("Test Author", author.Name!.DisplayName);
|
||||
Assert.Equal("Author", author.Role!.Name);
|
||||
Assert.Equal("Writing", author.Role.Category);
|
||||
Assert.Equal(MediaContributorRoleCategory.Author, author.Role.Category);
|
||||
|
||||
MediaContributorDto coAuthor = result.Contributors[1];
|
||||
Assert.Equal("Co Author", coAuthor.Name!.DisplayName);
|
||||
Assert.Equal("Author", coAuthor.Role!.Name);
|
||||
Assert.Equal("Writing", coAuthor.Role.Category);
|
||||
Assert.Equal(MediaContributorRoleCategory.Author, coAuthor.Role.Category);
|
||||
|
||||
MediaContributorDto translator = result.Contributors[2];
|
||||
Assert.Equal("Test Translator", translator.Name!.DisplayName);
|
||||
Assert.Equal("trl", translator.Role!.Name);
|
||||
Assert.Equal("Translation", translator.Role.Category);
|
||||
Assert.Equal(MediaContributorRoleCategory.Translator, translator.Role.Category);
|
||||
|
||||
MediaContributorDto illustrator = result.Contributors[3];
|
||||
Assert.Equal("Test Illustrator", illustrator.Name!.DisplayName);
|
||||
Assert.Equal("ill", illustrator.Role!.Name);
|
||||
Assert.Equal("Art", illustrator.Role.Category);
|
||||
Assert.Equal(MediaContributorRoleCategory.Illustrator, illustrator.Role.Category);
|
||||
|
||||
MediaContributorDto production = result.Contributors[4];
|
||||
Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", production.Name!.DisplayName);
|
||||
Assert.Equal("bkp", production.Role!.Name);
|
||||
Assert.Equal("Production", production.Role.Category);
|
||||
Assert.Equal(MediaContributorRoleCategory.Publisher, production.Role.Category);
|
||||
|
||||
MediaContributorDto misc = result.Contributors[5];
|
||||
Assert.Equal("Misc Contributor", misc.Name!.DisplayName);
|
||||
Assert.Equal("Contributor", misc.Role!.Name);
|
||||
Assert.Equal("Other", misc.Role.Category);
|
||||
Assert.Equal(MediaContributorRoleCategory.Other, misc.Role.Category);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+2
-1
@@ -6,6 +6,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.OpenLibrary.Core.Mapping;
|
||||
using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses;
|
||||
@@ -276,7 +277,7 @@ public class OpenLibraryMapperTests
|
||||
Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
|
||||
Assert.Contains(result.ISBNs!, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10);
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author" && contributor.Name.LegalName == "Test Personal Name" && contributor.Role!.Name == "Author");
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role!.Name == "Illustrator" && contributor.Role.Category == "Art");
|
||||
Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role!.Name == "Illustrator" && contributor.Role.Category == MediaContributorRoleCategory.Illustrator);
|
||||
BookRatingDto mappedRating = Assert.Single(result.Ratings!);
|
||||
Assert.Equal(4.2m, mappedRating.Value);
|
||||
Assert.Equal(5m, mappedRating.MaxValue);
|
||||
|
||||
Reference in new issue
Block a user