Adds unit tests improving infrastructure project code coverage

This commit is contained in:
BinaryAlley committed 2026-09-02 07:52:01 -07:00
1 parent ca2e7f9d97
commit 551259ad81
14 files changed
+2474

No files matched your search

@@ -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<CancellationToken>())
.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<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheConfiguredArtworkProviderIsNotRegistered_ShouldLogWarningAndSkipEnrichment()
{
// Arrange
Guid artworkPluginId = Guid.NewGuid();
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_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<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldSkipArtworkProvidersThatRequireWebAccess()
{
// Arrange
Guid webPluginId = Guid.NewGuid();
Guid localPluginId = Guid.NewGuid();
IArtworkProvider webProvider = Substitute.For<IArtworkProvider>();
webProvider.Name.Returns("Web Provider");
webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
webProvider.RequiresWebAccess.Returns(true);
IArtworkProvider localProvider = Substitute.For<IArtworkProvider>();
localProvider.Name.Returns("Local Provider");
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
localProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/local-cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
mockFileHashService.ComputeFileHash("/some/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<ILibraryRepository>();
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
_artworkConfigurationEntityFixture.Create(_libraryId.Value, webPluginId, 1),
_artworkConfigurationEntityFixture.Create(_libraryId.Value, localPluginId, 2)
]));
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<MetadataLookupDto>(), Arg.Any<CancellationToken>());
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<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to count the books that need artwork"));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the books that need artwork"));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the author display names"));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((ArtworkDto?)null);
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))];
SetupSingleBookPage(book, artworkPluginId);
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
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<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Storage.Error", "Failed to store the artwork"));
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
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<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Storage.Error", "Failed to store the artwork"));
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
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<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.RequiresWebAccess.Returns(true);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
mockFileHashService.ComputeFileHash(Arg.Any<string>()).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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// 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<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
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<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?>()));
// 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<ArtworkDto>(),
Arg.Any<CancellationToken>());
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<IArtworkProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<ArtworkDto?>(new InvalidOperationException("The artwork provider failed")));
IArtworkProvider secondProvider = Substitute.For<IArtworkProvider>();
secondProvider.Name.Returns("Second Provider");
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
secondProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
mockFileHashService.ComputeFileHash("/some/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<ILibraryRepository>();
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
_artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1),
_artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2)
]));
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// 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<IArtworkProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.RequiresWebAccess.Returns(false);
firstProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg"));
IArtworkProvider secondProvider = Substitute.For<IArtworkProvider>();
secondProvider.Name.Returns("Second Provider");
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
secondProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
mockFileHashService.ComputeFileHash("/some/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<ILibraryRepository>();
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
_artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1),
_artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2)
]));
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// 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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
IMediaLibraryScanJob mockChildJob = Substitute.For<IMediaLibraryScanJob>();
mockChildJob.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.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<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
/// <summary>
/// Wires a real service provider with the given artwork provider and services, so that the job resolves them from the dependency injection container.
/// </summary>
@@ -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<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenMarkingChangesSucceeds_ShouldExecuteTheChildJobs()
{
// Arrange
_mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
_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<CancellationToken>());
}
}
@@ -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<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheFilesToHashPageFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.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<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenUpdatingTheFileHashesFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf"), _hashedFileSystemFileDtoFixture.Create(path: "/books/book2.pdf")];
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(2));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList()));
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
.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<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheHashingCallbackRunsBeforeTheProgressInterval_ShouldNotPublishJobProgressFromTheCallback()
{
// Arrange
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")];
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(async callInfo =>
{
await callInfo.Arg<Func<Task>>()();
return callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList();
});
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
.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<IReadOnlyCollection<HashedFileSystemFileDto>>(files => files.All(file => file.CurrentHash == 42UL)),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheHashingCallbackRunsAfterTheProgressInterval_ShouldPublishJobProgressFromTheCallback()
{
// Arrange
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")];
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(async callInfo =>
{
await Task.Delay(150);
await callInfo.Arg<Func<Task>>()();
return callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList();
});
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
.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<LibraryScanJobProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload()
{
// Arrange
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(0));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
IMediaLibraryScanJob mockChildJob = Substitute.For<IMediaLibraryScanJob>();
mockChildJob.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.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<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
}
@@ -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<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)]));
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to count the books to enrich"));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)]));
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the books to enrich"));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<MetadataDto?>(new InvalidOperationException("The metadata provider failed")));
IMetadataProvider secondProvider = Substitute.For<IMetadataProvider>();
secondProvider.Name.Returns("Second Provider");
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
secondProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.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<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<MetadataDto?>(new InvalidOperationException("The metadata provider failed")));
IMetadataProvider secondProvider = Substitute.For<IMetadataProvider>();
secondProvider.Name.Returns("Second Provider");
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
secondProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.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<IMetadataProvider>();
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<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.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<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
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<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
MediaContributorDto contributorWithoutRole = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert") with { Role = null };
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.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<string?>(), Arg.Any<CancellationToken>())
.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<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author]));
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, firstPluginId);
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>())
.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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
IMediaLibraryScanJob mockChildJob = Substitute.For<IMediaLibraryScanJob>();
mockChildJob.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.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<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
/// <summary>
/// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container.
/// </summary>
@@ -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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.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<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.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<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.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<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.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<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenReadingUserSettingsFails_ShouldStillSeedTheFingerprintsAndComplete()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
SetupLibraryAndConfigurations(library);
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.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<CancellationToken>());
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<CancellationToken>());
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<IMediaLibraryScanJob>();
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.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<Guid>(), Arg.Is<object>(executedInput => executedInput == input), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<LibraryScanFinishedDomainEvent>(), Arg.Any<CancellationToken>());
}
/// <summary>
/// Stubs the repositories so that the job reads the provided library and its provider configurations.
/// </summary>
@@ -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<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenGettingChangedPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.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<Guid>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenApplyingSnapshotSwapFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(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<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenResettingEnrichmentStateFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["changed.pdf"]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.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<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(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<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingExistingBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["book1.pdf"]));
_mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any<string>(), Arg.Any<CancellationToken>())
.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<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenInsertingShellBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["book1.pdf"]));
_mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.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<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildWithoutPublishingFinishedEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.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<Guid>(), Arg.Is<object>(executedInput => executedInput == input), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<LibraryScanFinishedDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenBookPathYieldsEmptyDerivedTitle_ShouldFallBackToTheFileNameAsTitle()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["_.pdf"]));
_mockBookRepository.GetByPathAsync(_libraryId.Value, "_.pdf", Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<BookEntity>(book => book.Path == "_.pdf" && book.Title == "_"), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
}
@@ -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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>
{
[unchangedDirectoryFullName] = _directoryScanFingerprintEntityFixture.Create(
libraryId: _libraryId.Value,
path: unchangedDirectoryFullName,
lastWriteTimeUtc: unchangedDirectoryLastWriteTimeUtc)
}));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
_mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
.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<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities =>
entities.Count == 1 && Path.GetFileName(entities.Single().Path) == "book.pdf"),
Arg.Any<CancellationToken>());
await _mockDirectoryScanFingerprintRepository.Received(1).UpsertRangeAsync(
Arg.Is<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(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<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to load the directory scan fingerprints"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>()));
_mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
.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<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to insert the staging results"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDirectoryScanFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.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<Guid>(), Arg.Is<object>(executedInput => executedInput == input), Arg.Any<CancellationToken>());
}
/// <summary>
/// Test helper managing a temporary library directory, deleted when the test finishes.
/// </summary>
@@ -168,4 +168,65 @@ public class DebouncedMediaLibraryScanProgressNotifierTests
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Failed.ToString()),
Arg.Any<CancellationToken>());
}
[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<MediaLibraryScanCompositeId>());
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
}
[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<MediaLibraryScanCompositeId>());
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
}
[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<object?[]>(args => args.Length == 1
&& args[0] != null
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Completed.ToString()),
Arg.Any<CancellationToken>());
}
}
@@ -393,6 +393,262 @@ public class BookArtworkServiceTests
await Assert.ThrowsAnyAsync<OperationCanceledException>(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<FileSystemPathId>())
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
// Act
Result<string> 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<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("FileSystem.Error", "Failed to detect the image type"));
// Act
Result<string> 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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory"));
// Act
Result<string> 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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory"));
// Act
Result<string> 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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork"));
// Act
Result<string> 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<FileSystemPathId>(), Arg.Any<string>());
}
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<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork"));
// Act
Result<string> 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<FileSystemPathId>());
}
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<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.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<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.Arg<string>();
return name == $"{libraryName}-{libraryId}"
? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false))
: Errors.FileSystemManagement.InvalidPath;
});
// Act
Result<string> 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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>(), true)
.Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files"));
// Act
Result<Deleted> result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
[Fact]
public void DeleteBookArtwork_WhenCalled_ShouldDeleteTheCoverFilesInTheBookDirectory()
{
@@ -708,6 +708,81 @@ public class BookReadingServiceTests : IDisposable
}
}
[Fact]
public async Task GetSectionAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
// Act
Result<ReadingSectionDto> 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<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenAReaderDeclaresABlankExtension_ShouldSkipItAndStillResolveTheFormat()
{
// Arrange
ReadingDocumentDto document = CreateExtractableDocument();
StubOpenAsyncToExtract(document);
IBookReader blankExtensionReader = Substitute.For<IBookReader>();
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<IServiceScopeFactory>();
BookReadingService sut = new(serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For<ILogger<BookReadingService>>());
// Act
Result<ReadingManifestResponse> 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<bool> productionStarted = new();
TaskCompletionSource<bool> allowProductionToFinish = new();
_mockReader.GetResourceAsync(Arg.Any<string>(), Arg.Any<string>(), "cover", Arg.Any<CancellationToken>())
.Returns(async callInfo =>
{
productionStarted.SetResult(true);
await allowProductionToFinish.Task;
return producedResource;
});
// Act
Task<Result<ReadingResourceDataDto>> firstTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
await productionStarted.Task;
Task<Result<ReadingResourceDataDto>> secondTask = _sut.GetResourceAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "cover", shouldRenderPdfAsImages: false, CancellationToken.None);
allowProductionToFinish.SetResult(true);
Result<ReadingResourceDataDto> firstResult = await firstTask;
Result<ReadingResourceDataDto> 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<string>(), "cover", Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates a reading document whose spine and resources are extractable into the working directory.
/// </summary>
@@ -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<CancellationToken>())
.Returns(Result.Deleted);
_mockArtworkConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveProviderConfigurationsForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any<Guid>());
}
[Fact]
public async Task RemoveProviderConfigurationsAsync_WhenDeletingBookReadersFails_ShouldReturnError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
_mockMetadataConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtworkConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveProviderConfigurationsAsync(pluginId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any<Guid>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([existingConfiguration]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any<Guid>(), Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([existingConfiguration]));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any<Guid>(), Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Error.Failure(description: "Failed to read configurations"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([staleConfiguration]));
_mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
// Act
Result<Success> 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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockMetadataConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to persist the configuration"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to read configurations"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to persist the configuration"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([existingConfiguration]));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any<Guid>(), Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockMetadataConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to persist the configuration"));
// Act
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[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<CancellationToken>())
.Returns(Error.Failure(description: "Failed to read configurations"));
// Act
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates the store under test wired to the mocked dependencies, optionally registering the providers and book readers of the loaded plugins.
/// </summary>
@@ -144,6 +144,52 @@ public class FileHashServiceTests
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => 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<HashedFileSystemFileDto> inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)];
// Act
List<HashedFileSystemFileDto> 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);
}
/// <summary>
/// Test helper managing a temporary directory, deleted when the test finishes.
/// </summary>
@@ -436,6 +436,84 @@ public class ThemeDetectionSyncJobTests : IDisposable
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenBundledThemeArchiveFileCannotBeOpened_ShouldLogWarningAndContinue()
{
// Arrange
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
string missingArchivePath = Path.Combine(_testRootPath, "bundled", "missing.zip");
_mockThemeService.GetBundledThemeArchivePaths().Returns([missingArchivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(missingArchivePath, Arg.Any<CancellationToken>()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme"));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenBundledThemeArchivePathIsADirectory_ShouldLogWarningAndContinue()
{
// Arrange
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([]));
string directoryPath = Path.Combine(_testRootPath, "not-an-archive");
Directory.CreateDirectory(directoryPath);
_mockThemeService.GetBundledThemeArchivePaths().Returns([directoryPath]);
_mockThemeService.ReadManifestFromArchiveAsync(directoryPath, Arg.Any<CancellationToken>()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme"));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[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<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme, healthyTheme]));
_mockThemeService.HasThemePack("broken-theme").Returns(false);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any<CancellationToken>()).Returns(Error.Failure("Theme.Files", "restore failed"));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Error.Failure("Database.Error", "update failed"));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenCancellationIsRequestedWhileCleaningUp_ShouldLetTheCancellationPropagate()
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
_mockThemeService.HasThemePack("user-theme").Returns(false);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Deleted>>(new OperationCanceledException()));
// Act
Task executionTask = StartAndWaitForExecutionAsync(CreateSut());
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => executionTask);
await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any<CancellationToken>());
}
/// <summary>
/// Invokes the protected <see cref="BackgroundService.ExecuteAsync"/> of the job and awaits its completion.
/// </summary>
@@ -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<ThemeManifestDto> 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<ThemeManifestDto> 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<ThemeManifestDto> 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<string, string>(StringComparer.OrdinalIgnoreCase)
{
["default"] = "templates/../../escape.html"
});
byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", manifestJson));
// Act
Result<ThemeManifestDto> 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<ThemeManifestDto> 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<ThemeManifestDto> 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<ThemeManifestDto> 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<ThemeManifestDto> 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<ThemeManifestDto> 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<IPathService>();
pathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo =>
{
string segment = callInfo.Arg<string>();
string sanitized = segment == "assets" ? "renamed-assets" : segment;
return PathSegment.Create(sanitized, isDirectory: true, isDrive: false);
});
ThemeService sut = new(Options.Create(_options), Substitute.For<ILogger<ThemeService>>(), pathService);
// Act
Result<ThemeAssetDto> 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<Success> 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"));
}
/// <summary>
/// Cleans up the temporary storage used by the tests.
/// </summary>