mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 12:11:10 +00:00
Adds the media library artwork aggregation services, enrichers, and their provider contracts
This commit is contained in:
1 parent
00376c8313
commit
9e118864c3
33 files changed
+4621
-1118
No files matched your search
+252
@@ -0,0 +1,252 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArtworkService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtworkServiceTests
|
||||
{
|
||||
private readonly IEnvironmentContext _mockEnvironmentContext;
|
||||
private readonly IFileTypeService _mockFileTypeService;
|
||||
private readonly IFileProviderService _mockFileProviderService;
|
||||
private readonly IDirectoryProviderService _mockDirectoryProviderService;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly IHttpClientFactory _mockHttpClientFactory;
|
||||
private readonly IOptions<MediaSettingsDto> _mockMediaSettingsOptions;
|
||||
private readonly MusicArtworkService _sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly PathSegmentFixture _pathSegmentFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtworkServiceTests"/> class.
|
||||
/// </summary>
|
||||
public MusicArtworkServiceTests()
|
||||
{
|
||||
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
|
||||
_mockFileTypeService = Substitute.For<IFileTypeService>();
|
||||
_mockFileProviderService = Substitute.For<IFileProviderService>();
|
||||
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
|
||||
_mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
|
||||
_mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
|
||||
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
|
||||
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
|
||||
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
|
||||
|
||||
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books", musicDirectory: "music");
|
||||
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
|
||||
_mockMediaSettingsOptions.Value.Returns(mediaSettings);
|
||||
|
||||
_sut = new MusicArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
|
||||
MockPathBuilding();
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
MockPathBuilding();
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
|
||||
MockPathBuilding();
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("FileSystem.Error", result.FirstError.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteAlbumArtwork_WhenListingTheArtworkFilesFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
string albumTitle = "Test Album";
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files"));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("FileSystem.Error", result.FirstError.Code);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteAlbumArtwork_WhenCalled_ShouldDeleteEveryFileInTheAlbumDirectory()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
string albumTitle = "Test Album";
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
|
||||
FileSystemPathId bookletFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "booklet-1.jpg"));
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, bookletFileId]));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
|
||||
_mockFileProviderService.Received(1).DeleteFile(bookletFileId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteAlbumArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any<FileSystemPathId>(), true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteAlbumArtwork_WhenBuildingTheDirectoryPathFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path service so that building the artwork directory paths succeeds.
|
||||
/// </summary>
|
||||
private void MockPathBuilding()
|
||||
{
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
string name = callInfo.Arg<string>();
|
||||
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
|
||||
});
|
||||
|
||||
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path and file system services so that the artwork is stored into the given directory.
|
||||
/// </summary>
|
||||
/// <param name="artworkDirectoryPath">The file system path of the directory into which the artwork is stored.</param>
|
||||
private void MockArtworkDirectoryStubs(string artworkDirectoryPath)
|
||||
{
|
||||
MockPathBuilding();
|
||||
|
||||
// Every directory except the artwork directory itself already exists, so that only the final directory is created.
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>()))));
|
||||
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory that the artwork of the album is stored into.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <returns>The expected file system path of the album artwork directory.</returns>
|
||||
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle)
|
||||
{
|
||||
return Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"media",
|
||||
"music",
|
||||
$"{libraryName}-{libraryId}",
|
||||
artistName,
|
||||
$"{albumTitle}-{albumId}");
|
||||
}
|
||||
}
|
||||
+604
@@ -0,0 +1,604 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicMediaLibraryScanArtworkEnricher"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicMediaLibraryScanArtworkEnricherTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository;
|
||||
private readonly IArtistRepository _mockArtistRepository;
|
||||
private readonly IAlbumRepository _mockAlbumRepository;
|
||||
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
|
||||
private readonly IUserSettingsRepository _mockUserSettingsRepository;
|
||||
private readonly IMusicArtworkService _mockMusicArtworkService;
|
||||
private readonly IFileHashService _mockFileHashService;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly TestArtworkProvider<ArtistMetadataLookupDto> _artistProvider;
|
||||
private readonly TestArtworkProvider<AlbumMetadataLookupDto> _albumProvider;
|
||||
private readonly MusicMediaLibraryScanArtworkEnricher _sut;
|
||||
private readonly ServiceProvider _serviceProvider;
|
||||
private readonly Guid _artistPluginId = Guid.NewGuid();
|
||||
private readonly Guid _albumPluginId = Guid.NewGuid();
|
||||
private readonly LibraryId _libraryId;
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicMediaLibraryScanArtworkEnricherTests"/> class.
|
||||
/// </summary>
|
||||
public MusicMediaLibraryScanArtworkEnricherTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockArtworkProviderConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockArtistRepository = Substitute.For<IArtistRepository>();
|
||||
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
|
||||
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
|
||||
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository);
|
||||
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
|
||||
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
|
||||
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
|
||||
|
||||
_artistProvider = new TestArtworkProvider<ArtistMetadataLookupDto> { Name = "Artist Provider", RequiresWebAccess = false };
|
||||
_albumProvider = new TestArtworkProvider<AlbumMetadataLookupDto> { Name = "Album Provider", RequiresWebAccess = false };
|
||||
|
||||
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
|
||||
_mockFileHashService = Substitute.For<IFileHashService>();
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
|
||||
// the enricher resolves the keyed artwork providers from the scope of the service provider, and specializes them by the lookup they accept,
|
||||
// so a real container is used to honor the keyed registration of the typed providers.
|
||||
ServiceCollection services = new();
|
||||
services.AddScoped<IUnitOfWork>(_ => _mockUnitOfWork);
|
||||
services.AddScoped<IDomainEventPublisher>(_ => _mockDomainEventPublisher);
|
||||
services.AddSingleton(_mockMusicArtworkService);
|
||||
services.AddSingleton(_mockFileHashService);
|
||||
services.AddKeyedSingleton<IArtworkProvider>(_artistPluginId, _artistProvider);
|
||||
services.AddKeyedSingleton<IArtworkProvider>(_albumPluginId, _albumProvider);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
_sut = new MusicMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), NullLogger<MusicMediaLibraryScanArtworkEnricher>.Instance);
|
||||
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
|
||||
// Default stubs that keep the happy path working, overridden per test where needed.
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<UserSettingsEntity?>.Success(null));
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(0));
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ArtistEntity>>([]));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(0));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([]));
|
||||
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string>>(new Dictionary<Guid, string>()));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
SetupSuccessArtworkStorage();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryType_WhenCalled_ShouldReturnMusic()
|
||||
{
|
||||
// Act
|
||||
LibraryType result = _sut.SupportedLibraryType;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryType.Music, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Provider.Error", "Failed to read the configurations"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloads_ShouldSkipProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(canDownloadMetadataFromWeb: false);
|
||||
_artistProvider.RequiresWebAccess = true;
|
||||
_albumProvider.RequiresWebAccess = true;
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloadsButTheProviderIsLocal_ShouldStillResolve()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(canDownloadMetadataFromWeb: false);
|
||||
_artistProvider.RequiresWebAccess = true;
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupAlbums(album);
|
||||
_albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1, _albumProvider.CallCount);
|
||||
Assert.Equal(0, _artistProvider.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheArtistProviderReturnsArtwork_ShouldStoreAndPersistEnrichedArtistArtwork()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync(
|
||||
_libraryId.Value,
|
||||
Arg.Any<string>(),
|
||||
artist.Name,
|
||||
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artist.Id, Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
|
||||
&& entities.First().OwnerType == MusicArtworkOwnerType.Artist
|
||||
&& entities.First().OwnerId == artist.Id
|
||||
&& entities.First().ArtworkType == ArtworkType.Cover
|
||||
&& entities.First().Ordinal == 0
|
||||
&& entities.First().Status == ArtworkStatus.Enriched
|
||||
&& entities.First().Provider == "Artist Provider"
|
||||
&& entities.First().FileName == "/media/music/cover.jpg"
|
||||
&& entities.First().ContentHash == 123UL),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumProviderReturnsArtwork_ShouldStoreAndPersistEnrichedAlbumArtwork()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupAlbums(album);
|
||||
_albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
|
||||
_libraryId.Value,
|
||||
album.Id,
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
album.Title,
|
||||
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
|
||||
Arg.Any<CancellationToken>(),
|
||||
Arg.Any<string?>());
|
||||
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, album.Id, Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
|
||||
&& entities.First().OwnerType == MusicArtworkOwnerType.Album
|
||||
&& entities.First().OwnerId == album.Id
|
||||
&& entities.First().Status == ArtworkStatus.Enriched
|
||||
&& entities.First().Provider == "Album Provider"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheProviderAnswersWithNoArtwork_ShouldMarkTheArtistNotAvailable()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
|
||||
&& entities.First().Status == ArtworkStatus.NotAvailable
|
||||
&& entities.First().FileName == null
|
||||
&& entities.First().Provider == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheArtistFailed()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromException<IReadOnlyList<ArtworkDto>>(new HttpRequestException("Transient failure."));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheArtistFailed()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Artwork.Error", "Failed to store the artwork"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenClearingTheStoredArtworkFilesFails_ShouldLeaveTheArtistUnresolved()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork files"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenClearingTheStoredArtworkRecordsFails_ShouldLeaveTheArtistUnresolved()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork records"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumHasNoMusicBrainzIdentifierAndNoLocalProvider_ShouldLeaveItUnresolved()
|
||||
{
|
||||
// Arrange
|
||||
_albumProvider.RequiresWebAccess = true;
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
libraryId: _libraryId.Value,
|
||||
includeMusicBrainzReleaseId: false,
|
||||
includeMusicBrainzReleaseGroupId: false);
|
||||
SetupAlbums(album);
|
||||
_albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(0, _albumProvider.CallCount);
|
||||
await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumCountCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to count the albums"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumsPageCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to read the albums"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheTrackPathsCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
|
||||
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to read the track paths"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to save the changes"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the media library reader with a library owned by the test user.
|
||||
/// </summary>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the library allows downloading data from the web.</param>
|
||||
private void SetupLibrary(bool canDownloadMetadataFromWeb = true)
|
||||
{
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Music,
|
||||
canDownloadMetadataFromWeb: canDownloadMetadataFromWeb);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork provider configuration reader with one enabled configuration per test plugin.
|
||||
/// </summary>
|
||||
private void SetupConfiguration()
|
||||
{
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(
|
||||
[
|
||||
_artworkConfigurationFixture.Create(_libraryId.Value, _artistPluginId, 0),
|
||||
_artworkConfigurationFixture.Create(_libraryId.Value, _albumPluginId, 1)
|
||||
]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artist reader with a single page holding the provided artists.
|
||||
/// </summary>
|
||||
/// <param name="artists">The artists of the page.</param>
|
||||
private void SetupArtists(params ArtistEntity[] artists)
|
||||
{
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(artists.Length));
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<ArtistEntity>>(artists),
|
||||
Result.From<IReadOnlyList<ArtistEntity>>([]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the album reader with a single page holding the provided albums.
|
||||
/// </summary>
|
||||
/// <param name="albums">The albums of the page.</param>
|
||||
private void SetupAlbums(params AlbumEntity[] albums)
|
||||
{
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(albums.Length));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<AlbumEntity>>(albums),
|
||||
Result.From<IReadOnlyList<AlbumEntity>>([]));
|
||||
Dictionary<Guid, string> trackPaths = albums.ToDictionary(album => album.Id, album => "/music/artist/album/track.flac");
|
||||
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string>>(trackPaths));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork storage and persistence so that an item is stored successfully.
|
||||
/// </summary>
|
||||
private void SetupSuccessArtworkStorage()
|
||||
{
|
||||
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/music/cover.jpg"));
|
||||
_mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>(), Arg.Any<string?>())
|
||||
.Returns(Result.From("/media/music/cover.jpg"));
|
||||
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>()).Returns(Result.Deleted);
|
||||
_mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>()).Returns(Result.Deleted);
|
||||
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
|
||||
_mockMusicArtworkRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
_mockFileHashService.ComputeFileHash(Arg.Any<string>()).Returns(123UL);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deterministic artwork provider for a specific lookup type, used instead of a substitute because the default implementation of
|
||||
/// <see cref="IArtworkProvider.GetArtworkAsync(MetadataLookupDto, CancellationToken)"/> cannot be intercepted reliably.
|
||||
/// </summary>
|
||||
/// <typeparam name="TLookup">The type of the lookup the provider accepts.</typeparam>
|
||||
private sealed class TestArtworkProvider<TLookup> : IArtworkProvider<TLookup> where TLookup : MetadataLookupDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the display name of the artwork provider.
|
||||
/// </summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the media library types this artwork provider supports.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes { get; set; } = [LibraryType.Music];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
|
||||
/// </summary>
|
||||
public bool RequiresWebAccess { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the callback that supplies the artwork of a media item.
|
||||
/// </summary>
|
||||
public Func<TLookup, CancellationToken, Task<IReadOnlyList<ArtworkDto>>> OnGetArtworkAsync { get; set; } = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of times the provider was asked for artwork.
|
||||
/// </summary>
|
||||
public int CallCount { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artworks of the media item described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to get the artwork for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artworks of the media item, or an empty collection when no artwork was found.</returns>
|
||||
public Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
CallCount++;
|
||||
return OnGetArtworkAsync(lookup, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
-733
@@ -1,18 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
@@ -23,17 +13,13 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -50,19 +36,14 @@ public class MediaLibraryScanArtworkEnrichmentJobTests
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMediaLibraryScanArtworkEnricher _mockArtworkEnricher;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<MediaLibraryScanArtworkEnrichmentJob> _mockLogger;
|
||||
private readonly MediaLibraryScanArtworkEnrichmentJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
@@ -79,23 +60,27 @@ public class MediaLibraryScanArtworkEnrichmentJobTests
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
// the job resolves the artwork enricher of the loaded library type from the service scope, so the music enricher must be available
|
||||
_mockArtworkEnricher = Substitute.For<IMediaLibraryScanArtworkEnricher>();
|
||||
_mockArtworkEnricher.SupportedLibraryType.Returns(LibraryType.Music);
|
||||
_mockArtworkEnricher.EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanArtworkEnricher>))
|
||||
.Returns(new IMediaLibraryScanArtworkEnricher[] { _mockArtworkEnricher });
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_mockLogger = Substitute.For<ILogger<MediaLibraryScanArtworkEnrichmentJob>>();
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory, _mockLogger)
|
||||
_sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
@@ -104,729 +89,39 @@ public class MediaLibraryScanArtworkEnrichmentJobTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndTrackTheCoverArtworkAsEnriched()
|
||||
public async Task ExecuteAsync_WhenEnrichmentSucceeds_ShouldPublishProgressChangedEvent()
|
||||
{
|
||||
// Arrange
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul);
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title");
|
||||
SetupSingleBookPage(book, artworkPluginId);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Music);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await mockBookArtworkService.Received(1).SaveBookArtworkAsync(
|
||||
_libraryId.Value,
|
||||
book.Id,
|
||||
"My Library",
|
||||
"Frank Herbert",
|
||||
"Test Title",
|
||||
Arg.Any<ArtworkDto>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity coverArtwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType);
|
||||
Assert.Equal(0, coverArtwork.Ordinal);
|
||||
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
|
||||
Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName);
|
||||
Assert.Equal(123ul, coverArtwork.ContentHash);
|
||||
Assert.Equal("Artwork Provider", coverArtwork.Provider);
|
||||
Assert.NotNull(coverArtwork.LastUpdateUtc);
|
||||
await _mockArtworkEnricher.Received(1).EnrichAsync(_libraryId, _scanId, _userId, Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenResolvedArtworkIsIdenticalToTheStoredOne_ShouldKeepTheStoredArtworkAndMarkItAsEnriched()
|
||||
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul);
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
// the book already has a stored cover with the same content hash as the resolved artwork
|
||||
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))];
|
||||
SetupSingleBookPage(book, artworkPluginId);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the identical artwork is not copied again, so the artwork storage service is not called and the stored file name is kept
|
||||
await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity coverArtwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
|
||||
Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName);
|
||||
Assert.Equal("Artwork Provider", coverArtwork.Provider);
|
||||
Assert.NotNull(coverArtwork.LastUpdateUtc);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoProviderReturnsArtwork_ShouldMarkTheCoverArtworkAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((ArtworkDto?)null);
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, artworkPluginId);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity coverArtwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType);
|
||||
Assert.Equal(0, coverArtwork.Ordinal);
|
||||
Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status);
|
||||
Assert.Null(coverArtwork.FileName);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichmentWithoutMarkingBooksAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// a library without artwork providers must not mark its books as failed to resolve, so the books are not even queried
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
[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, cancellationToken: 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(Result.Success);
|
||||
|
||||
// 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.Artwork);
|
||||
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(Result.Success);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(null));
|
||||
|
||||
// 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(Result.Success);
|
||||
|
||||
// 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, cancellationToken: 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(Result.Success);
|
||||
|
||||
// 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.Artwork = [_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.Artwork);
|
||||
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.Artwork);
|
||||
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.Artwork = [_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.Artwork);
|
||||
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.Artwork);
|
||||
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.Artwork = [_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.Artwork);
|
||||
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, cancellationToken: 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(Result.Success);
|
||||
_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.Artwork);
|
||||
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, cancellationToken: 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(Result.Success);
|
||||
_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.Artwork);
|
||||
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(Result.Success);
|
||||
|
||||
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>
|
||||
/// <param name="artworkPluginId">The Id of the plugin providing the artwork.</param>
|
||||
/// <param name="artworkProvider">The artwork provider to resolve.</param>
|
||||
/// <param name="bookArtworkService">The service used to store the artwork of the books.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork.</param>
|
||||
private void SetupRealServiceProvider(Guid artworkPluginId, IArtworkProvider artworkProvider, IBookArtworkService bookArtworkService, IFileHashService fileHashService)
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
services.AddSingleton(bookArtworkService);
|
||||
services.AddSingleton(fileHashService);
|
||||
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
|
||||
ServiceProvider realServiceProvider = services.BuildServiceProvider();
|
||||
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the repositories so that the job processes a single page containing the given book, configured with the given artwork provider.
|
||||
/// </summary>
|
||||
/// <param name="book">The book whose artwork the job must resolve.</param>
|
||||
/// <param name="artworkPluginId">The Id of the plugin configured as artwork provider for the library.</param>
|
||||
private void SetupSingleBookPage(BookEntity book, Guid artworkPluginId)
|
||||
{
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)
|
||||
]));
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
await _mockArtworkEnricher.DidNotReceive().EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+482
@@ -0,0 +1,482 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksMediaLibraryScanArtworkEnricher"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BooksMediaLibraryScanArtworkEnricherTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IArtworkProvider _mockArtworkProvider;
|
||||
private readonly IBookArtworkService _mockBookArtworkService;
|
||||
private readonly IFileHashService _mockFileHashService;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<BooksMediaLibraryScanArtworkEnricher> _mockLogger;
|
||||
private readonly BooksMediaLibraryScanArtworkEnricher _sut;
|
||||
private readonly ServiceProvider _serviceProvider;
|
||||
private readonly Guid _pluginId = Guid.NewGuid();
|
||||
private readonly LibraryId _libraryId;
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanArtworkEnricherTests"/> class.
|
||||
/// </summary>
|
||||
public BooksMediaLibraryScanArtworkEnricherTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockArtworkProviderConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
_mockArtworkProvider = Substitute.For<IArtworkProvider>();
|
||||
_mockArtworkProvider.Name.Returns("Test Provider");
|
||||
_mockArtworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(true);
|
||||
|
||||
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
_mockFileHashService = Substitute.For<IFileHashService>();
|
||||
_mockFileHashService.ComputeFileHash(Arg.Any<string>()).Returns(123UL);
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockLogger = Substitute.For<ILogger<BooksMediaLibraryScanArtworkEnricher>>();
|
||||
|
||||
// The enricher resolves the keyed artwork providers from the scope of the service provider, so a real container is used to honor the keyed registration.
|
||||
ServiceCollection services = new();
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
services.AddSingleton(_mockBookArtworkService);
|
||||
services.AddSingleton(_mockFileHashService);
|
||||
services.AddKeyedSingleton<IArtworkProvider>(_pluginId, _mockArtworkProvider);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
_sut = new BooksMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), _mockLogger);
|
||||
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryType_WhenCalled_ShouldReturnBook()
|
||||
{
|
||||
// Act
|
||||
LibraryType result = _sut.SupportedLibraryType;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryType.Book, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Provider.Error", "Failed to read the configurations"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloads_ShouldSkipProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(canDownloadMetadataFromWeb: false);
|
||||
SetupConfiguration();
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(true);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloadsButTheProviderIsLocal_ShouldStillResolve()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(canDownloadMetadataFromWeb: false);
|
||||
SetupConfiguration();
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(false);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtworkProvider.Received(1).GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheBookHasArtwork_ShouldStoreAndPersistEnrichedArtwork()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg", type: ArtworkType.Cover, ordinal: 0)]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(
|
||||
book.LibraryId,
|
||||
book.Id,
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
book.Title,
|
||||
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkType.Cover, artwork.ArtworkType);
|
||||
Assert.Equal(0, artwork.Ordinal);
|
||||
Assert.Equal(ArtworkStatus.Enriched, artwork.Status);
|
||||
Assert.Equal("Test Provider", artwork.Provider);
|
||||
Assert.Equal("/media/books/cover.jpg", artwork.FileName);
|
||||
Assert.Equal(123UL, artwork.ContentHash);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenAProviderAnswersWithNoArtwork_ShouldMarkTheBookFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
|
||||
Assert.Null(artwork.FileName);
|
||||
Assert.Null(artwork.Provider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheBookFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<IReadOnlyList<ArtworkDto>>(new HttpRequestException("Transient failure.")));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheProviderReturnsRemoteArtworkButDoesNotRequireWebAccess_ShouldMarkTheBookFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheStoredArtworkIsIdentical_ShouldKeepItAndMarkItEnriched()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
BookArtworkEntity existingArtwork = _bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, contentHash: 123UL, status: ArtworkStatus.Enriched);
|
||||
book.Artwork = [existingArtwork];
|
||||
SetupBooks(book);
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/media/books/local.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Enriched, artwork.Status);
|
||||
Assert.Equal("Test Provider", artwork.Provider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheBookFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
_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("Artwork.Error", "Failed to store the artwork"));
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheBookCountCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to count the books"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheBooksPageCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to read the books"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAuthorsCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to read the authors"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to save the changes"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
SetupBooks();
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the media library reader with a library owned by the test user.
|
||||
/// </summary>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the library allows downloading data from the web.</param>
|
||||
private void SetupLibrary(bool canDownloadMetadataFromWeb = true)
|
||||
{
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Book,
|
||||
canDownloadMetadataFromWeb: canDownloadMetadataFromWeb);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork provider configuration reader with a single enabled configuration for the test plugin.
|
||||
/// </summary>
|
||||
private void SetupConfiguration()
|
||||
{
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationFixture.Create(_libraryId.Value, _pluginId, 0)]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the book reader with a single page holding the provided books.
|
||||
/// </summary>
|
||||
/// <param name="books">The books of the page.</param>
|
||||
private void SetupBooks(params BookEntity[] books)
|
||||
{
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(books.Length));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<BookEntity>>(books),
|
||||
Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
Dictionary<Guid, string?> authors = books.ToDictionary(book => book.Id, book => (string?)"Frank Herbert");
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(authors));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork storage so that a book stores its artwork successfully.
|
||||
/// </summary>
|
||||
private void SetupSuccessStore()
|
||||
{
|
||||
_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/cover.jpg"));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -144,7 +144,7 @@ public class BookArtworkServiceTests
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
|
||||
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
|
||||
FileSystemPathId otherFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "metadata.json"));
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, otherFileId]));
|
||||
|
||||
Reference in new issue
Block a user