diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs index 0f511bba..0a23ca9f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs @@ -17,6 +17,7 @@ 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.Services.Jobs; 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; @@ -253,6 +254,538 @@ public class MediaLibraryScanArtworkEnrichmentJobTests Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + [Fact] + public async Task ExecuteAsync_WhenReadingArtworkProviderConfigurationsFails_ShouldLogWarningAndSkipEnrichment() + { + // Arrange + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to read the artwork provider configurations")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a failure to read the artwork configurations is best-effort, so the enrichment is skipped without touching the books + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheConfiguredArtworkProviderIsNotRegistered_ShouldLogWarningAndSkipEnrichment() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + + // the configuration references a plugin that is not registered in the dependency injection container + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1)])); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldSkipArtworkProvidersThatRequireWebAccess() + { + // Arrange + Guid webPluginId = Guid.NewGuid(); + Guid localPluginId = Guid.NewGuid(); + IArtworkProvider webProvider = Substitute.For(); + webProvider.Name.Returns("Web Provider"); + webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + webProvider.RequiresWebAccess.Returns(true); + IArtworkProvider localProvider = Substitute.For(); + localProvider.Name.Returns("Local Provider"); + localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + localProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/local-cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/local-cover.jpg").Returns(111UL); + + ServiceCollection services = new(); + services.AddKeyedSingleton(webPluginId, webProvider); + services.AddKeyedSingleton(localPluginId, localProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(mockBookArtworkService); + services.AddSingleton(mockFileHashService); + // 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); + + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: false))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([ + _artworkConfigurationEntityFixture.Create(_libraryId.Value, webPluginId, 1), + _artworkConfigurationEntityFixture.Create(_libraryId.Value, localPluginId, 2) + ])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the provider that requires access to the web is skipped when the library does not permit web downloads + await webProvider.DidNotReceive().GetArtworkAsync(Arg.Any(), Arg.Any()); + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("Local Provider", coverArtwork.Provider); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenCountingTheBooksNeedingArtworkFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to count the books that need artwork")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheBooksNeedingArtworkFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the books that need artwork")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheAuthorDisplayNamesFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the author display names")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenNoProviderReturnsArtworkAndTheBookHasAnExistingCover_ShouldMarkTheExistingCoverAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns((ArtworkDto?)null); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + 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>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); + Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenStoringTheArtworkFailsAndTheBookHasNoExistingCover_ShouldTrackTheCoverAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Storage.Error", "Failed to store the artwork")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(111UL); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, artworkPluginId); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); + Assert.Null(coverArtwork.FileName); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenStoringTheArtworkFailsAndTheBookHasAnExistingCover_ShouldMarkTheExistingCoverAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Storage.Error", "Failed to store the artwork")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(222UL); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; + SetupSingleBookPage(book, artworkPluginId); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); + Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheResolvedArtworkIsRemote_ShouldComputeTheContentHashOfTheStoredArtwork() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.RequiresWebAccess.Returns(true); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash(Arg.Any()).Returns(999UL); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, artworkPluginId); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // for remote artwork, the content hash is computed on the stored copy, so it is only known after the artwork is stored + await mockBookArtworkService.Received(1).SaveBookArtworkAsync(_libraryId.Value, book.Id, "My Library", "Frank Herbert", Arg.Any(), Arg.Any(), Arg.Any()); + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); + Assert.Equal(999ul, coverArtwork.ContentHash); + Assert.Equal("Artwork Provider", coverArtwork.Provider); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheBookHasAnExistingCoverAndTheArtworkDiffersFromIt_ShouldStoreItAndUpdateTheExistingCover() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(222UL); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + // the book has no known ISBNs of its own, so the artwork lookup is built without an ISBN + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title", includeMetadata: false); + book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; + SetupSingleBookPage(book, artworkPluginId); + // the author of the book is not known, so its artwork directory falls back to an empty author name + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary())); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await mockBookArtworkService.Received(1).SaveBookArtworkAsync( + _libraryId.Value, + book.Id, + "My Library", + string.Empty, + "Test Title", + Arg.Any(), + Arg.Any()); + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); + Assert.Equal(222ul, coverArtwork.ContentHash); + Assert.Equal("Artwork Provider", coverArtwork.Provider); + Assert.NotNull(coverArtwork.LastUpdateUtc); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAnArtworkProviderThrows_ShouldTryTheNextProvider() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IArtworkProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new InvalidOperationException("The artwork provider failed"))); + IArtworkProvider secondProvider = Substitute.For(); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/second-cover.jpg").Returns(333UL); + + ServiceCollection services = new(); + services.AddKeyedSingleton(firstPluginId, firstProvider); + services.AddKeyedSingleton(secondPluginId, secondProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(mockBookArtworkService); + services.AddSingleton(mockFileHashService); + // 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); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([ + _artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1), + _artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2) + ])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a failing artwork provider must not prevent the artwork of the other provider from being used + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("Second Provider", coverArtwork.Provider); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAProviderReturnsRemoteArtworkWithoutRequiringWebAccess_ShouldSkipItAndUseTheNextProvider() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IArtworkProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.RequiresWebAccess.Returns(false); + firstProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg")); + IArtworkProvider secondProvider = Substitute.For(); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/second-cover.jpg").Returns(444UL); + + ServiceCollection services = new(); + services.AddKeyedSingleton(firstPluginId, firstProvider); + services.AddKeyedSingleton(secondPluginId, secondProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(mockBookArtworkService); + services.AddSingleton(mockFileHashService); + // 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); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([ + _artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1), + _artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2) + ])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a provider that returns remote artwork must require web access, so its artwork is skipped and the next provider is used + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("Second Provider", coverArtwork.Provider); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload() + { + // Arrange + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + IMediaLibraryScanJob mockChildJob = Substitute.For(); + mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChildJob); + Guid id = Guid.NewGuid(); + object input = new(); + + // Act + await _sut.ExecuteAsync(id, input, CancellationToken.None); + + // Assert + await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + /// /// Wires a real service provider with the given artwork provider and services, so that the job resolves them from the dependency injection container. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs index 7d107d7b..8b60619f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs @@ -5,6 +5,7 @@ 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.Services.Jobs; 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; @@ -122,4 +123,23 @@ public class MediaLibraryScanDiffJobTests await Assert.ThrowsAnyAsync(() => operation); Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + + [Fact] + public async Task ExecuteAsync_WhenMarkingChangesSucceeds_ShouldExecuteTheChildJobs() + { + // Arrange + _mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + IMediaLibraryScanJob mockChild = Substitute.For(); + _sut.AddChild(mockChild); + Guid id = Guid.NewGuid(); + object input = new(); + + // Act + await _sut.ExecuteAsync(id, input, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await mockChild.Received(1).ExecuteAsync(id, input, Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs index cc07e71a..8fb60013 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs @@ -7,6 +7,7 @@ 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.Services.Jobs; 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; @@ -170,4 +171,144 @@ public class MediaLibraryScanHashJobTests await Assert.ThrowsAnyAsync(() => operation); Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheFilesToHashPageFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the files to hash")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenUpdatingTheFileHashesFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + List filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf"), _hashedFileSystemFileDtoFixture.Create(path: "/books/book2.pdf")]; + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(2)); + _mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(filesToHash), + Result.From>([])); + _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()) + .Returns(callInfo => Task.FromResult(callInfo.Arg>() + .Select(file => file with { CurrentHash = 42UL }) + .ToList())); + _mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to update the file hashes")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockFileHashService.Received(1).HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheHashingCallbackRunsBeforeTheProgressInterval_ShouldNotPublishJobProgressFromTheCallback() + { + // Arrange + List filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")]; + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(filesToHash), + Result.From>([])); + _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()) + .Returns(async callInfo => + { + await callInfo.Arg>()(); + return callInfo.Arg>() + .Select(file => file with { CurrentHash = 42UL }) + .ToList(); + }); + _mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.Received(1).UpdateFileHashesAsync( + _scanId.Value, + Arg.Is>(files => files.All(file => file.CurrentHash == 42UL)), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheHashingCallbackRunsAfterTheProgressInterval_ShouldPublishJobProgressFromTheCallback() + { + // Arrange + List filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")]; + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(filesToHash), + Result.From>([])); + _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()) + .Returns(async callInfo => + { + await Task.Delay(150); + await callInfo.Arg>()(); + return callInfo.Arg>() + .Select(file => file with { CurrentHash = 42UL }) + .ToList(); + }); + _mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + // the initial progress and the progress published from the hashing callback are both reported + await _mockDomainEventPublisher.Received(2).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload() + { + // Arrange + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(0)); + _mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + IMediaLibraryScanJob mockChildJob = Substitute.For(); + mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChildJob); + Guid id = Guid.NewGuid(); + object input = new(); + + // Act + await _sut.ExecuteAsync(id, input, CancellationToken.None); + + // Assert + await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs index 343f32c5..01776927 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs @@ -25,6 +25,7 @@ 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.Services.Jobs; 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; @@ -488,6 +489,223 @@ public class MediaLibraryScanMetadataEnrichmentJobTests Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } + [Fact] + public async Task ExecuteAsync_WhenCountingTheBooksNeedingMetadataFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to count the books to enrich")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheBooksPageNeedingMetadataFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the books to enrich")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAMetadataProviderThrowsWhileTryingTheProvidersInOrder_ShouldTryTheNextProvider() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new InvalidOperationException("The metadata provider failed"))); + IMetadataProvider secondProvider = Substitute.For(); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId, secondPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a failing metadata provider must not prevent the metadata of the next provider from being used + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal("Second Provider", book.MetadataProvider); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAMetadataProviderThrowsWhileAggregatingMetadata_ShouldUseTheFindingsOfTheOtherProviders() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new InvalidOperationException("The metadata provider failed"))); + IMetadataProvider secondProvider = Substitute.For(); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId, secondPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal("Second Provider", book.MetadataProvider); + Assert.Equal("Second Title", book.Title); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAContributorHasNoDisplayName_ShouldSkipLinkingIt() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + MediaContributorDto namelessContributor = _mediaContributorDtoFixture.Create(roleName: "Author", roleCategory: MediaContributorRoleCategory.Author) with { Name = null }; + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [namelessContributor])); + + 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 + // a contributor without a display name cannot be linked to the book, so no contributor is queried or created + await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); + Assert.Empty(book.BookContributors); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAContributorHasNoRole_ShouldLinkItWithTheDefaultRole() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + MediaContributorDto contributorWithoutRole = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert") with { Role = null }; + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [contributorWithoutRole])); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", includeMetadata: false); + SetupSingleBookPage(book, firstPluginId); + + MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) + .Returns(Result.From(authorEntity)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + BookContributorEntity linkedContributor = Assert.Single(book.BookContributors); + Assert.Equal("Contributor", linkedContributor.RoleName); + Assert.Equal(MediaContributorRoleCategory.Other, linkedContributor.RoleCategory); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenFindingOrCreatingAContributorFails_ShouldMarkJobAsFailed() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + 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(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to find or create the contributor")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload() + { + // Arrange + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + IMediaLibraryScanJob mockChildJob = Substitute.For(); + mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChildJob); + Guid id = Guid.NewGuid(); + object input = new(); + + // Act + await _sut.ExecuteAsync(id, input, CancellationToken.None); + + // Assert + await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + /// /// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs index 2ec4efc1..ff984873 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs @@ -14,6 +14,7 @@ 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.Services.Jobs; 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; @@ -249,6 +250,161 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + [Fact] + public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(null)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingMetadataConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the metadata provider configurations")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingArtworkConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the artwork provider configurations")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenResettingMetadataStatusFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: null); + SetupLibraryAndConfigurations(library); + _mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to reset the metadata status")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenResettingArtworkStatusFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: "STALE_ARTWORK"); + SetupLibraryAndConfigurations(library); + _mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to reset the artwork status")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenReadingUserSettingsFails_ShouldStillSeedTheFingerprintsAndComplete() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); + mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to read the user settings")); + _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // reading the user settings is best effort, a failure must not prevent the fingerprints from being persisted + Assert.NotNull(library.MetadataProvidersConfigurationFingerprint); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenUserSettingsRepositoryIsNotRegistered_ShouldSeedTheFingerprintsAndComplete() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + _mockUnitOfWork.UserSettingsRepository.Returns((IUserSettingsRepository)null!); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the user settings repository is optional, its absence must not prevent the fingerprints from being persisted + Assert.NotNull(library.MetadataProvidersConfigurationFingerprint); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildAndComplete() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + + IMediaLibraryScanJob mockChild = Substitute.For(); + mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChild); + object input = new(); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await mockChild.Received(1).ExecuteAsync(Arg.Any(), Arg.Is(executedInput => executedInput == input), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + /// /// Stubs the repositories so that the job reads the provided library and its provider configurations. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs index e1f9c3a9..7704dc1a 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs @@ -7,6 +7,7 @@ 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.Services.Jobs; 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; @@ -200,4 +201,202 @@ public class MediaLibraryScanResultsSaveJobTests await Assert.ThrowsAnyAsync(() => operation); Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + + [Fact] + public async Task ExecuteAsync_WhenGettingChangedPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the changed paths")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockSnapshotRepository.DidNotReceive().ApplySnapshotSwapAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenApplyingSnapshotSwapFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to apply the snapshot swap")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenResettingEnrichmentStateFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>(["changed.pdf"])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to reset the enrichment state")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the paths")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingExistingBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>(["book1.pdf"])); + _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the existing book")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenInsertingShellBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>(["book1.pdf"])); + _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to insert the shell book")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildWithoutPublishingFinishedEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + IMediaLibraryScanJob mockChild = Substitute.For(); + mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChild); + object input = new(); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await mockChild.Received(1).ExecuteAsync(Arg.Any(), Arg.Is(executedInput => executedInput == input), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenBookPathYieldsEmptyDerivedTitle_ShouldFallBackToTheFileNameAsTitle() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>(["_.pdf"])); + _mockBookRepository.GetByPathAsync(_libraryId.Value, "_.pdf", Arg.Any()) + .Returns(Result.From(null)); + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Created)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the file name is made only of separators, so the derived title is empty and the raw file name is used as a fallback + await _mockBookRepository.Received(1).InsertAsync(Arg.Is(book => book.Path == "_.pdf" && book.Title == "_"), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs index 04b5f70f..86a3f0a8 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs @@ -6,6 +6,7 @@ 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.Services.Jobs; 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; @@ -46,6 +47,7 @@ public class BooksFileSystemDiscoveryJobTests private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; private readonly LibraryId _libraryId; @@ -177,6 +179,185 @@ public class BooksFileSystemDiscoveryJobTests Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + [Fact] + public async Task ExecuteAsync_WhenFastSkipIsEnabledAndDirectoryDidNotChange_ShouldSkipTheDirectoryAndUpsertOnlyChangedFingerprints() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + string unchangedDirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("unchanged"); + File.WriteAllText(Path.Combine(unchangedDirectoryPath, "skip.pdf"), "unchanged book content"); + string changedDirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("changed"); + File.WriteAllText(Path.Combine(changedDirectoryPath, "book.pdf"), "changed book content"); + + DirectoryInfo unchangedDirectory = new(unchangedDirectoryPath); + string unchangedDirectoryFullName = unchangedDirectory.FullName; + DateTime unchangedDirectoryLastWriteTimeUtc = unchangedDirectory.LastWriteTimeUtc; + DirectoryInfo changedDirectory = new(changedDirectoryPath); + string changedDirectoryFullName = changedDirectory.FullName; + DirectoryInfo rootDirectory = new(temporaryLibraryDirectory.Path); + string rootDirectoryFullName = rootDirectory.FullName; + + LibraryEntity libraryEntity = _libraryEntityFixture.Create( + id: _libraryId.Value, + userId: _userId.Value, + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: [temporaryLibraryDirectory.Path], + shouldSkipUnchangedDirectoriesDuringScan: true); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(libraryEntity)); + _mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(new Dictionary + { + [unchangedDirectoryFullName] = _directoryScanFingerprintEntityFixture.Create( + libraryId: _libraryId.Value, + path: unchangedDirectoryFullName, + lastWriteTimeUtc: unchangedDirectoryLastWriteTimeUtc) + })); + _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Created)); + _mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => + entities.Count == 1 && Path.GetFileName(entities.Single().Path) == "book.pdf"), + Arg.Any()); + await _mockDirectoryScanFingerprintRepository.Received(1).UpsertRangeAsync( + Arg.Is>(entities => + entities.Count == 2 + && entities.Any(entity => entity.Path == rootDirectoryFullName) + && entities.Any(entity => entity.Path == changedDirectoryFullName) + && entities.All(entity => entity.Path != unchangedDirectoryFullName) + && entities.All(entity => entity.LibraryId == _libraryId.Value)), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLoadingDirectoryScanFingerprintsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + LibraryEntity libraryEntity = _libraryEntityFixture.Create( + id: _libraryId.Value, + userId: _userId.Value, + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: [temporaryLibraryDirectory.Path], + shouldSkipUnchangedDirectoriesDuringScan: true); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(libraryEntity)); + _mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to load the directory scan fingerprints")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenUpsertingDirectoryScanFingerprintsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + temporaryLibraryDirectory.CreateSubdirectory("changed"); + LibraryEntity libraryEntity = _libraryEntityFixture.Create( + id: _libraryId.Value, + userId: _userId.Value, + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: [temporaryLibraryDirectory.Path], + shouldSkipUnchangedDirectoriesDuringScan: true); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(libraryEntity)); + _mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(new Dictionary())); + _mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to upsert the directory scan fingerprints")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenInsertingStagingResultsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + temporaryLibraryDirectory.CreateFile("book.pdf", "book content"); + LibraryEntity libraryEntity = _libraryEntityFixture.Create( + id: _libraryId.Value, + userId: _userId.Value, + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: [temporaryLibraryDirectory.Path], + shouldSkipUnchangedDirectoriesDuringScan: false); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(libraryEntity)); + _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to insert the staging results")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDirectoryScanFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildAndComplete() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + temporaryLibraryDirectory.CreateFile("book1.pdf", "book content"); + LibraryEntity libraryEntity = _libraryEntityFixture.Create( + id: _libraryId.Value, + userId: _userId.Value, + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: [temporaryLibraryDirectory.Path], + shouldSkipUnchangedDirectoriesDuringScan: false); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(libraryEntity)); + _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Created)); + + IMediaLibraryScanJob mockChild = Substitute.For(); + mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _sut.AddChild(mockChild); + object input = new(); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await mockChild.Received(1).ExecuteAsync(Arg.Any(), Arg.Is(executedInput => executedInput == input), Arg.Any()); + } + /// /// Test helper managing a temporary library directory, deleted when the test finishes. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs index 1a5ff63f..09778c31 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs @@ -168,4 +168,65 @@ public class DebouncedMediaLibraryScanProgressNotifierTests && ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Failed.ToString()), Arg.Any()); } + + [Fact] + public async Task SendLibraryScanFinishedEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await _sut.SendLibraryScanFinishedEventAsync(compositeId, cancellationTokenSource.Token); + + // Assert + _mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any()); + _mockHubClients.DidNotReceive().Group(Arg.Any()); + } + + [Fact] + public async Task SendLibraryScanFailedEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await _sut.SendLibraryScanFailedEventAsync(compositeId, cancellationTokenSource.Token); + + // Assert + _mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any()); + _mockHubClients.DidNotReceive().Group(Arg.Any()); + } + + [Fact] + public async Task SendLibraryScanFinishedEventAsync_WhenADebouncedUpdateWasScheduledForTheScan_ShouldRemoveTheDebouncer() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + // The scheduled update is registered by the progress update even when the progress is missing, which also avoids sending an update event. + _mockProgressTracker.GetScanProgress(compositeId) + .Returns(Error.Failure("Tracking.Error", "The scan progress is missing")); + MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create( + scanId: compositeId.ScanId, + userId: compositeId.UserId, + completedJobs: 1, + totalJobs: 2, + status: LibraryScanJobStatus.Running); + _mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress)); + + // Act + await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None); + await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None); + + // Assert + await _mockClientProxy.Received(1).SendCoreAsync( + "libraryScanFinishedEvent", + Arg.Is(args => args.Length == 1 + && args[0] != null + && ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Completed.ToString()), + Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs index 6f8cb8d8..0e3a93f3 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs @@ -393,6 +393,262 @@ public class BookArtworkServiceTests await Assert.ThrowsAnyAsync(Act); } + [Fact] + public async Task SaveBookArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg"); + _mockFileProviderService.FileExists(Arg.Any()) + .Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenImageTypeDetectionFails_ShouldReturnTheError() + { + // Arrange + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("FileSystem.Error", "Failed to detect the image type")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenCreatingTheArtworkDirectoryFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Directory.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenDirectoryExistenceCheckFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Directory.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenCopyingTheArtworkFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().RenameFile(Arg.Any(), Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRenamingTheCopiedArtworkFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork")); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenAuthorNameCannotBeSanitized_ShouldReturnInvalidPath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media"); + string booksPath = Path.Combine(mediaRoot, "books"); + _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot)); + _mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath)); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return name == $"{libraryName}-{libraryId}" + ? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)) + : Errors.FileSystemManagement.InvalidPath; + }); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public void DeleteBookArtwork_WhenListingTheCoverFilesFails_ShouldReturnSuccessAndDeleteNothing() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files")); + + // Act + Result result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + [Fact] public void DeleteBookArtwork_WhenCalled_ShouldDeleteTheCoverFilesInTheBookDirectory() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs index 3c06b4b0..6fd720f6 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/BookReadingServiceTests.cs @@ -708,6 +708,81 @@ public class BookReadingServiceTests : IDisposable } } + [Fact] + public async Task GetSectionAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError() + { + // Arrange + _mockPluginManager.GetPlugins().Returns([]); + + // Act + Result result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError); + await _mockReader.DidNotReceive().OpenAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetManifestAsync_WhenAReaderDeclaresABlankExtension_ShouldSkipItAndStillResolveTheFormat() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + IBookReader blankExtensionReader = Substitute.For(); + blankExtensionReader.SupportedExtensions.Returns([" "]); + blankExtensionReader.SupportedLibraryTypes.Returns([LibraryType.EBook]); + ServiceCollection services = new(); + services.AddKeyedSingleton(_pluginId, blankExtensionReader); + services.AddKeyedSingleton(_pluginId, _mockReader); + services.AddSingleton(_mockUnitOfWork); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + IServiceScopeFactory serviceScopeFactory = serviceProvider.GetRequiredService(); + BookReadingService sut = new(serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For>()); + + // Act + Result result = await sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(document.Title, result.Value.Title); + } + } + + [Fact] + public async Task GetResourceAsync_WhenTwoRequestsMissTheSameResourceConcurrently_ShouldProduceItOnceAndBothServeIt() + { + // Arrange + ReadingDocumentDto document = CreateExtractableDocument(); + StubOpenAsyncToExtract(document); + byte[] producedResource = [7, 8, 9]; + TaskCompletionSource productionStarted = new(); + TaskCompletionSource allowProductionToFinish = new(); + _mockReader.GetResourceAsync(Arg.Any(), Arg.Any(), "cover", Arg.Any()) + .Returns(async callInfo => + { + productionStarted.SetResult(true); + await allowProductionToFinish.Task; + return producedResource; + }); + + // Act + Task> firstTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + await productionStarted.Task; + Task> secondTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None); + allowProductionToFinish.SetResult(true); + Result firstResult = await firstTask; + Result secondResult = await secondTask; + + // Assert + Assert.False(firstResult.IsFailure); + Assert.False(secondResult.IsFailure); + Assert.Equal(new byte[] { 7, 8, 9 }, firstResult.Value.Data); + Assert.Equal(new byte[] { 7, 8, 9 }, secondResult.Value.Data); + await _mockReader.Received(1).GetResourceAsync(_bookPath, Arg.Any(), "cover", Arg.Any()); + } + /// /// Creates a reading document whose spine and resources are extractable into the working directory. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs index 9d3f049e..d44a916c 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs @@ -736,6 +736,279 @@ public class MediaLibraryProviderConfigurationStoreTests Assert.True(result.IsFailure); } + [Fact] + public async Task RemoveProviderConfigurationsForLibraryAsync_WhenDeletingBookReadersFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtworkConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.Deleted); + _mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveProviderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + _mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any()); + } + + [Fact] + public async Task RemoveProviderConfigurationsAsync_WhenDeletingBookReadersFails_ShouldReturnError() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtworkConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Result.Deleted); + _mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveProviderConfigurationsAsync(pluginId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + _mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenMetadataProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.EBook), null, null)); + LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, pluginId, 1); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockMetadataConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenArtworkProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.EBook), null)); + LibraryArtworkProviderConfigurationEntity existingConfiguration = _artworkConfigurationFixture.Create(libraryId, pluginId, 1); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockArtworkConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenReadingMetadataConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.EBook), null, null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to read configurations")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenDeletingStaleMetadataConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + LibraryMetadataProviderConfigurationEntity staleConfiguration = _metadataConfigurationFixture.Create(libraryId, pluginId, 1); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([staleConfiguration])); + _mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete the configurations")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenUpsertingMetadataConfigurationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.EBook), null, null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to persist the configuration")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenReadingArtworkConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.EBook), null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to read configurations")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenUpsertingArtworkConfigurationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.EBook), null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to persist the configuration")); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ReconcileBookReaderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldKeepItWithoutUpserting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub"))); + LibraryBookReaderConfigurationEntity existingConfiguration = _bookReaderConfigurationFixture.Create(libraryId: libraryId, pluginId: pluginId); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task EnsureProviderConfigurationsAsync_WhenUpsertingMetadataConfigurationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to persist the configuration")); + + // Act + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureProviderConfigurationsAsync_WhenReadingArtworkConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Book), null)); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to read configurations")); + + // Act + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + /// /// Creates the store under test wired to the mocked dependencies, optionally registering the providers and book readers of the loaded plugins. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/FileHashServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/FileHashServiceTests.cs index 0b32baa0..20f5673d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/FileHashServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/FileHashServiceTests.cs @@ -144,6 +144,52 @@ public class FileHashServiceTests await Assert.ThrowsAnyAsync(() => operation); } + [Fact] + public void ComputeFileHash_WhenFileIsEmpty_ShouldReturnEmptyFileHash() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath = temporaryTestDirectory.CreateFile("empty.pdf", string.Empty); + + // Act + ulong hash = _sut.ComputeFileHash(filePath); + + // Assert + Assert.Equal(BitConverter.ToUInt64(new XxHash64().GetCurrentHash()), hash); + } + + [Fact] + public void ComputeFileHash_WhenFileHasContent_ShouldReturnNonZeroHash() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath = temporaryTestDirectory.CreateFile("book.pdf", "content of the book"); + + // Act + ulong hash = _sut.ComputeFileHash(filePath); + + // Assert + Assert.NotEqual(0UL, hash); + } + + [Fact] + public async Task HashFilesAsync_WhenFileIsLargerThanTheSamplingThreshold_ShouldSampleTheWholeFile() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath = Path.Combine(temporaryTestDirectory.Path, "large.pdf"); + File.WriteAllBytes(filePath, new byte[500_000]); + List inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)]; + + // Act + List result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None); + + // Assert + HashedFileSystemFileDto hashedFile = Assert.Single(result); + Assert.Equal(filePath, hashedFile.Path); + Assert.NotEqual(0UL, hashedFile.CurrentHash); + } + /// /// Test helper managing a temporary directory, deleted when the test finishes. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs index 2892bf8f..9c12665e 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs @@ -436,6 +436,84 @@ public class ThemeDetectionSyncJobTests : IDisposable await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task StartAsync_WhenBundledThemeArchiveFileCannotBeOpened_ShouldLogWarningAndContinue() + { + // Arrange + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + string missingArchivePath = Path.Combine(_testRootPath, "bundled", "missing.zip"); + _mockThemeService.GetBundledThemeArchivePaths().Returns([missingArchivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(missingArchivePath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledThemeArchivePathIsADirectory_ShouldLogWarningAndContinue() + { + // Arrange + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + string directoryPath = Path.Combine(_testRootPath, "not-an-archive"); + Directory.CreateDirectory(directoryPath); + _mockThemeService.GetBundledThemeArchivePaths().Returns([directoryPath]); + _mockThemeService.ReadManifestFromArchiveAsync(directoryPath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenSoftDeletingUnrestorableBundledThemeFails_ShouldLogWarningAndContinue() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "broken-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); + ThemeEntity healthyTheme = _themeEntityFixture.Create(themeId: "healthy-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme, healthyTheme])); + _mockThemeService.HasThemePack("broken-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Database.Error", "update failed")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenCancellationIsRequestedWhileCleaningUp_ShouldLetTheCancellationPropagate() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); + _mockThemeService.HasThemePack("user-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()) + .Returns(Task.FromException>(new OperationCanceledException())); + + // Act + Task executionTask = StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await Assert.ThrowsAnyAsync(() => executionTask); + await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any()); + } + /// /// Invokes the protected of the job and awaits its completion. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs index 89114f94..ea59c768 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -1200,6 +1200,243 @@ public class ThemeServiceTests : IDisposable Assert.False(_sut.HasThemePack("bundled-theme")); } + [Fact] + public async Task InstallAsync_WhenArchiveContainsAllowedDirectoryEntries_ShouldInstallSuccessfully() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("templates/", string.Empty), + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("assets/preview.png", "preview-image-bytes")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.True(_sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsDisallowedDirectoryEntry_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("notes/", string.Empty)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("not allowed", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveDoesNotContainThemeJson_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("theme.json", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenTemplatePathFailsNormalization_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/../../escape.html" + }); + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", manifestJson)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "Theme path segment"); + } + + [Fact] + public async Task InstallAsync_WhenPreviewPathFailsNormalization_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(preview: "../../outside.png"); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "Theme path segment"); + } + + [Fact] + public async Task InstallAsync_WhenManifestContainsNullLiteral_ShouldReturnInvalidJsonError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "null")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); + Assert.Contains("no manifest object", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenStorageRootCannotBeCreated_ShouldReturnThemeFilesUnreadable() + { + // Arrange + string blockedRootPath = Path.Combine(_testRootPath, "blocked-storage"); + File.WriteAllText(blockedRootPath, "a file occupies the storage root path"); + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: blockedRootPath, + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250); + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.Create(); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenStagingDirectoryContainsStaleEntries_ShouldRemoveThemBeforeInstalling() + { + // Arrange + Directory.CreateDirectory(_options.StoragePath); + Directory.CreateDirectory(Path.Combine(_options.StoragePath, ".staging")); + File.WriteAllText(Path.Combine(_options.StoragePath, ".staging", "stale.txt"), "stale"); + Directory.CreateDirectory(Path.Combine(_options.StoragePath, ".staging", "old")); + File.WriteAllText(Path.Combine(_options.StoragePath, ".staging", "old", "inner.txt"), "stale"); + byte[] archive = _themePackFixture.Create(); + + // Act + await InstallValidThemeAsync(archive); + + // Assert + Assert.True(_sut.HasThemePack("test-theme")); + Assert.False(File.Exists(Path.Combine(_options.StoragePath, ".staging", "stale.txt"))); + Assert.False(Directory.Exists(Path.Combine(_options.StoragePath, ".staging", "old"))); + } + + [Fact] + public async Task LoadManifestAsync_WhenThemeDirectoryExistsButManifestWasRemoved_ShouldReturnMissingManifestError() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create(themeId: "removed-manifest-theme")); + File.Delete(Path.Combine(_options.StoragePath, "removed-manifest-theme", "theme.json")); + + // Act + Result result = await _sut.LoadManifestAsync("removed-manifest-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("missing theme.json", result.FirstError.Description); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenManifestContainsNullLiteral_ShouldReturnInvalidJsonError() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "null-manifest.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "null"))); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); + Assert.Contains("no manifest object", result.FirstError.Description); + } + + [Fact] + public async Task GetAssetAsync_WhenPathSegmentIsRenamedByPathService_ShouldReturnPackageInvalidError() + { + // Arrange + IPathService pathService = Substitute.For(); + pathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string segment = callInfo.Arg(); + string sanitized = segment == "assets" ? "renamed-assets" : segment; + return PathSegment.Create(sanitized, isDirectory: true, isDrive: false); + }); + ThemeService sut = new(Options.Create(_options), Substitute.For>(), pathService); + + // Act + Result result = await sut.GetAssetAsync("test-theme", "assets/logo.png", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenThemeDestinationIsBlocked_ShouldReturnThemeFilesUnreadable() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "restore-blocked.zip"), _themePackFixture.Create(themeId: "restore-blocked")); + Directory.CreateDirectory(_options.StoragePath); + File.WriteAllText(Path.Combine(_options.StoragePath, "restore-blocked"), "blocked"); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("restore-blocked", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + Assert.False(_sut.HasThemePack("restore-blocked")); + } + + [Fact] + public void Constructor_WhenConfiguredPathsAreRelative_ShouldResolveThemAgainstTheBaseDirectory() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250); + options.StoragePath = $"relative-themes-{Guid.NewGuid():N}"; + options.BundledThemesPath = $"relative-bundled-{Guid.NewGuid():N}"; + + // Act + ThemeService sut = CreateSut(options); + + // Assert + Assert.False(sut.HasThemePack("not-installed")); + } + /// /// Cleans up the temporary storage used by the tests. ///