mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 20:11:10 +00:00
Adds the music library scanning pipeline, its scanner, scan jobs, and path structure
This commit is contained in:
1 parent
9e118864c3
commit
35ac1dbdcb
38 files changed
+5119
-1150
No files matched your search
+149
@@ -0,0 +1,149 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
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 NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicLibraryTypeScanner"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicLibraryTypeScannerTests
|
||||
{
|
||||
private readonly IMediaLibraryScanJobFactory _mockJobFactory = Substitute.For<IMediaLibraryScanJobFactory>();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryType_ShouldBeMusic()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act & Assert
|
||||
Assert.Equal(LibraryType.Music, sut.SupportedLibraryType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobChainWithEnrichmentJobs()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
TestScanJob discoveryJob = CreateJob<IMusicFileSystemDiscoveryJob>();
|
||||
TestScanJob diffJob = CreateJob<IMediaLibraryScanDiffJob>();
|
||||
TestScanJob hashJob = CreateJob<IMediaLibraryScanHashJob>();
|
||||
TestScanJob metadataExtractionJob = CreateJob<IMusicMetadataExtractionJob>();
|
||||
TestScanJob saveJob = CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
TestScanJob invalidationJob = CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
TestScanJob enrichmentJob = CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
TestScanJob artworkEnrichmentJob = CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
List<IMediaLibraryScanJob> rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId)];
|
||||
|
||||
// Assert
|
||||
IMediaLibraryScanJob rootJob = Assert.Single(rootJobs);
|
||||
Assert.Same(discoveryJob, rootJob);
|
||||
Assert.Contains(diffJob, discoveryJob.Children);
|
||||
Assert.Contains(discoveryJob, diffJob.Parents);
|
||||
Assert.Contains(hashJob, diffJob.Children);
|
||||
Assert.Contains(diffJob, hashJob.Parents);
|
||||
Assert.Contains(metadataExtractionJob, hashJob.Children);
|
||||
Assert.Contains(hashJob, metadataExtractionJob.Parents);
|
||||
Assert.Contains(saveJob, metadataExtractionJob.Children);
|
||||
Assert.Contains(metadataExtractionJob, saveJob.Parents);
|
||||
Assert.Contains(invalidationJob, saveJob.Children);
|
||||
Assert.Contains(saveJob, invalidationJob.Parents);
|
||||
Assert.Contains(enrichmentJob, invalidationJob.Children);
|
||||
Assert.Contains(invalidationJob, enrichmentJob.Parents);
|
||||
Assert.Contains(artworkEnrichmentJob, enrichmentJob.Children);
|
||||
Assert.Contains(enrichmentJob, artworkEnrichmentJob.Parents);
|
||||
_mockJobFactory.Received(1).CreateJob<IMusicMetadataExtractionJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
CreateJob<IMusicFileSystemDiscoveryJob>();
|
||||
CreateJob<IMediaLibraryScanDiffJob>();
|
||||
CreateJob<IMediaLibraryScanHashJob>();
|
||||
CreateJob<IMusicMetadataExtractionJob>();
|
||||
CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
MusicLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
_ = sut.CreateScanJobsForLibrary(libraryId).ToList();
|
||||
|
||||
// Assert
|
||||
_mockJobFactory.Received(1).CreateJob<IMusicFileSystemDiscoveryJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanDiffJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanHashJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMusicMetadataExtractionJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanResultsSaveJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
private TestScanJob CreateJob<TJob>() where TJob : class, IMediaLibraryScanJob
|
||||
{
|
||||
TestScanJob job = new()
|
||||
{
|
||||
ScanId = _scanIdFixture.Create(),
|
||||
UserId = _userIdFixture.Create(),
|
||||
LibraryId = _libraryIdFixture.Create()
|
||||
};
|
||||
_mockJobFactory.CreateJob<TJob>(Arg.Any<LibraryId>()).Returns((TJob)(object)job);
|
||||
return job;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Concrete test implementation of the abstract <see cref="MediaLibraryScanJob"/> class that satisfies all job interfaces.
|
||||
/// </summary>
|
||||
private sealed class TestScanJob : MediaLibraryScanJob,
|
||||
IMusicFileSystemDiscoveryJob,
|
||||
IMediaLibraryScanDiffJob,
|
||||
IMediaLibraryScanHashJob,
|
||||
IMusicMetadataExtractionJob,
|
||||
IMediaLibraryScanResultsSaveJob,
|
||||
IMediaLibraryScanProviderConfigurationInvalidationJob,
|
||||
IMediaLibraryScanMetadataEnrichmentJob,
|
||||
IMediaLibraryScanArtworkEnrichmentJob
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public override Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-3
@@ -44,6 +44,7 @@ public class FileSystemStructureSeedServiceTests
|
||||
// Arrange
|
||||
_mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries"));
|
||||
_mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books"));
|
||||
_mockPathService.CombinePath(_rootPath, "music").Returns(Path.Combine(_rootPath, "music"));
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(false);
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result<FileSystemPathId>.Success(FileSystemPathId.Create(Path.Combine(_rootPath, callInfo.ArgAt<string>(1))).Value));
|
||||
@@ -53,8 +54,11 @@ public class FileSystemStructureSeedServiceTests
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
_mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any<FileSystemPathId>());
|
||||
_mockDirectoryProviderService.Received(2).CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
_mockDirectoryProviderService.Received(3).DirectoryExists(Arg.Any<FileSystemPathId>());
|
||||
_mockDirectoryProviderService.Received(3).CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
_mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any<FileSystemPathId>(), "libraries");
|
||||
_mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any<FileSystemPathId>(), "books");
|
||||
_mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any<FileSystemPathId>(), "music");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -63,6 +67,7 @@ public class FileSystemStructureSeedServiceTests
|
||||
// Arrange
|
||||
_mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries"));
|
||||
_mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books"));
|
||||
_mockPathService.CombinePath(_rootPath, "music").Returns(Path.Combine(_rootPath, "music"));
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(true);
|
||||
|
||||
// Act
|
||||
@@ -70,7 +75,7 @@ public class FileSystemStructureSeedServiceTests
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
_mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any<FileSystemPathId>());
|
||||
_mockDirectoryProviderService.Received(3).DirectoryExists(Arg.Any<FileSystemPathId>());
|
||||
_mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
|
||||
+25
-25
@@ -224,29 +224,29 @@ public class LibraryPathTemplateServiceTests
|
||||
public void Parse_WhenRelativePathIsEmpty_ShouldReturnNull(string relativePath)
|
||||
{
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, CreateMusicTemplate(), relativePath, '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, CreateMusicTemplate(), relativePath, '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
Assert.False(result.Value.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenTemplateIsEmpty_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, LibraryPathTemplate.Empty(), "Pink Floyd/1973 - Time.mp3", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, LibraryPathTemplate.Empty(), "Pink Floyd/1973 - Time.mp3", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
Assert.False(result.Value.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_WhenTemplateIsNotSupportedForTheLibraryType_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Book, CreateMusicTemplate(), "Pink Floyd/1973 - Time.mp3", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Book, CreateMusicTemplate(), "Pink Floyd/1973 - Time.mp3", '/');
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
@@ -261,11 +261,11 @@ public class LibraryPathTemplateServiceTests
|
||||
LibraryPathTemplate template = CreateMusicTemplate();
|
||||
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/1973 - Time.mp3", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/1973 - Time.mp3", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
ParsedLibraryPath parsedPath = result.Value!;
|
||||
ParsedLibraryPath parsedPath = result.Value.Value;
|
||||
Assert.Equal("Pink Floyd", parsedPath.GetString(LibraryPathPartKind.Artist).Value);
|
||||
Assert.Equal(1973, parsedPath.GetInt(LibraryPathPartKind.ReleaseYear).Value);
|
||||
Assert.Equal("Time", parsedPath.GetString(LibraryPathPartKind.TrackName).Value);
|
||||
@@ -280,11 +280,11 @@ public class LibraryPathTemplateServiceTests
|
||||
LibraryPathTemplate template = CreateMusicTemplate();
|
||||
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/no year/Time.mp3", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/no year/Time.mp3", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
Assert.False(result.Value.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -305,11 +305,11 @@ public class LibraryPathTemplateServiceTests
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/07", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/07", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(7, result.Value!.GetInt(LibraryPathPartKind.TrackNumber).Value);
|
||||
Assert.Equal(7, result.Value.Value.GetInt(LibraryPathPartKind.TrackNumber).Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -330,11 +330,11 @@ public class LibraryPathTemplateServiceTests
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/007", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/007", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
Assert.False(result.Value.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -351,11 +351,11 @@ public class LibraryPathTemplateServiceTests
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "1973", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "1973", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(1973, result.Value!.GetInt(LibraryPathPartKind.ReleaseYear).Value);
|
||||
Assert.Equal(1973, result.Value.Value.GetInt(LibraryPathPartKind.ReleaseYear).Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -372,11 +372,11 @@ public class LibraryPathTemplateServiceTests
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "73", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "73", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
Assert.False(result.Value.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -397,12 +397,12 @@ public class LibraryPathTemplateServiceTests
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Pink Floyd", result.Value!.GetString(LibraryPathPartKind.Artist).Value);
|
||||
Assert.False(result.Value.GetInt(LibraryPathPartKind.DiscNumber).HasValue);
|
||||
Assert.Equal("Pink Floyd", result.Value.Value.GetString(LibraryPathPartKind.Artist).Value);
|
||||
Assert.False(result.Value.Value.GetInt(LibraryPathPartKind.DiscNumber).HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -423,12 +423,12 @@ public class LibraryPathTemplateServiceTests
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/02", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/02", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Pink Floyd", result.Value!.GetString(LibraryPathPartKind.Artist).Value);
|
||||
Assert.Equal(2, result.Value.GetInt(LibraryPathPartKind.DiscNumber).Value);
|
||||
Assert.Equal("Pink Floyd", result.Value.Value.GetString(LibraryPathPartKind.Artist).Value);
|
||||
Assert.Equal(2, result.Value.Value.GetInt(LibraryPathPartKind.DiscNumber).Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -452,11 +452,11 @@ public class LibraryPathTemplateServiceTests
|
||||
]);
|
||||
|
||||
// Act
|
||||
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Tolkien/The Lord of the Rings - J.R.R. Tolkien", '/');
|
||||
Result<Optional<ParsedLibraryPath>> result = _sut.Parse(LibraryType.Music, template, "Tolkien/The Lord of the Rings - J.R.R. Tolkien", '/');
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Tolkien", result.Value!.GetString(LibraryPathPartKind.Author).Value);
|
||||
Assert.Equal("Tolkien", result.Value.Value.GetString(LibraryPathPartKind.Author).Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+18
-1
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
@@ -33,6 +34,23 @@ public class MediaLibraryScannerFactoryTests
|
||||
Assert.Same(expectedScanner, scanner);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateLibraryScanner_WhenLibraryTypeIsMusic_ShouldReturnMusicLibraryTypeScanner()
|
||||
{
|
||||
// Arrange
|
||||
IMusicLibraryTypeScanner expectedScanner = Substitute.For<IMusicLibraryTypeScanner>();
|
||||
ServiceCollection services = new();
|
||||
services.AddSingleton(expectedScanner);
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
MediaLibraryScannerFactory sut = new(serviceProvider);
|
||||
|
||||
// Act
|
||||
IMediaTypeScanner scanner = sut.CreateLibraryScanner(LibraryType.Music);
|
||||
|
||||
// Assert
|
||||
Assert.Same(expectedScanner, scanner);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LibraryType.EBook)] // eBook scanner is not implemented
|
||||
[InlineData(LibraryType.ComicBook)] // comic book scanner is not implemented
|
||||
@@ -55,7 +73,6 @@ public class MediaLibraryScannerFactoryTests
|
||||
[InlineData(LibraryType.InterviewVideo)] // interview video scanner is not implemented
|
||||
[InlineData(LibraryType.CoverSongVideo)] // cover song video scanner is not implemented
|
||||
[InlineData(LibraryType.PodcastVideo)] // podcast video scanner is not implemented
|
||||
[InlineData(LibraryType.Music)] // music scanner is not implemented
|
||||
[InlineData(LibraryType.Audiobook)] // audiobook scanner is not implemented
|
||||
[InlineData(LibraryType.LiveRecordingAudio)] // live recording audio scanner is not implemented
|
||||
[InlineData(LibraryType.InterviewAudio)] // interview audio scanner is not implemented
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicMetadataAggregator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicMetadataAggregatorTests
|
||||
{
|
||||
private readonly ArtistMetadataDtoFixture _artistMetadataDtoFixture = new();
|
||||
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
|
||||
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
|
||||
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
|
||||
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenMergingArtistMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorDto firstContributor = _mediaContributorDtoFixture.Create();
|
||||
MediaContributorDto secondContributor = _mediaContributorDtoFixture.Create();
|
||||
ArtistMetadataDto first = _artistMetadataDtoFixture.Create(name: "First", includeCountry: false, contributors: [firstContributor], genres: []);
|
||||
ArtistMetadataDto second = _artistMetadataDtoFixture.Create(name: "Second", country: "CA", contributors: [secondContributor], genres: []);
|
||||
|
||||
// Act
|
||||
ArtistMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("First", merged.Name);
|
||||
Assert.Equal("CA", merged.Country);
|
||||
Assert.Equal(2, merged.Contributors!.Count);
|
||||
Assert.Contains(merged.Contributors, contributor => contributor == firstContributor);
|
||||
Assert.Contains(merged.Contributors, contributor => contributor == secondContributor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenFirstArtistHasTheValue_ShouldNotTakeTheSecondValue()
|
||||
{
|
||||
// Arrange
|
||||
ArtistMetadataDto first = _artistMetadataDtoFixture.Create(name: "First", country: "US", genres: [], contributors: []);
|
||||
ArtistMetadataDto second = _artistMetadataDtoFixture.Create(name: "Second", country: "CA", genres: [], contributors: []);
|
||||
|
||||
// Act
|
||||
ArtistMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("First", merged.Name);
|
||||
Assert.Equal("US", merged.Country);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenMergingAlbumMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond()
|
||||
{
|
||||
// Arrange
|
||||
AlbumMetadataDto first = _albumMetadataDtoFixture.Create(title: "First", includeBarcode: false, includeReleaseInfo: false);
|
||||
AlbumMetadataDto second = _albumMetadataDtoFixture.Create(title: "Second", barcode: "1234567890123");
|
||||
|
||||
// Act
|
||||
AlbumMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("First", merged.Title);
|
||||
Assert.Equal("1234567890123", merged.Barcode);
|
||||
Assert.NotNull(merged.ReleaseInfo);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenMergingAudioMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond()
|
||||
{
|
||||
// Arrange
|
||||
AudioMetadataDto first = _audioMetadataDtoFixture.Create(title: "First", includeDurationInSeconds: false);
|
||||
AudioMetadataDto second = _audioMetadataDtoFixture.Create(title: "Second", durationInSeconds: 360);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("First", merged.Title);
|
||||
Assert.Equal(360, merged.DurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenTheFirstMetadataHasOnlyAReleaseYearAndTheSecondHasAReleaseDate_ShouldDeriveTheYearFromTheDate()
|
||||
{
|
||||
// Arrange
|
||||
// The tags of a compilation provide a release year without a full date, while MusicBrainz provides the original release date of the recording.
|
||||
ReleaseInfoDto firstReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseYear: 1981);
|
||||
ReleaseInfoDto secondReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(1975, 10, 31), originalReleaseYear: 1975);
|
||||
AudioMetadataDto first = _audioMetadataDtoFixture.Create(releaseInfo: firstReleaseInfo);
|
||||
AudioMetadataDto second = _audioMetadataDtoFixture.Create(releaseInfo: secondReleaseInfo);
|
||||
|
||||
// Act
|
||||
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
// The merged date and year must describe the same point in time, otherwise the release information would be rejected when applied.
|
||||
Assert.NotNull(merged.ReleaseInfo);
|
||||
Assert.Equal(new DateOnly(1975, 10, 31), merged.ReleaseInfo!.OriginalReleaseDate);
|
||||
Assert.Equal(1975, merged.ReleaseInfo.OriginalReleaseYear);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothAudioMetadataHaveIsrcs_ShouldUnionThemWithoutDuplicates()
|
||||
{
|
||||
// Arrange
|
||||
AudioMetadataDto first = _audioMetadataDtoFixture.Create();
|
||||
AudioMetadataDto second = _audioMetadataDtoFixture.Create();
|
||||
AudioMetadataDto mergedInput = first with { Isrcs = [.. first.Isrcs!.Concat(second.Isrcs!)] };
|
||||
|
||||
// Act
|
||||
AudioMetadataDto merged = MusicMetadataAggregator.Merge(mergedInput, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(mergedInput.Isrcs!.Select(isrc => isrc.Value).Distinct(StringComparer.OrdinalIgnoreCase).Count(), merged.Isrcs!.Count);
|
||||
}
|
||||
}
|
||||
+379
@@ -0,0 +1,379 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
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.Audio.Music;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicFileSystemDiscoveryJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicFileSystemDiscoveryJobTests
|
||||
{
|
||||
private const string ROOT_PATH = @"C:\Music";
|
||||
private const string AUDIO_FILE_PATH = @"C:\Music\song.mp3";
|
||||
private const string IMAGE_FILE_PATH = @"C:\Music\cover.jpg";
|
||||
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
|
||||
private readonly IDirectoryScanFingerprintRepository _mockFingerprintRepository;
|
||||
private readonly IFileProviderService _mockFileProviderService;
|
||||
private readonly IDirectoryProviderService _mockDirectoryProviderService;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MusicFileSystemDiscoveryJob _sut;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly DirectoryScanFingerprintEntityFixture _fingerprintFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryId _libraryId;
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicFileSystemDiscoveryJobTests"/> class.
|
||||
/// </summary>
|
||||
public MusicFileSystemDiscoveryJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockFingerprintRepository = Substitute.For<IDirectoryScanFingerprintRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockUnitOfWork.DirectoryScanFingerprintRepository.Returns(_mockFingerprintRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockFileProviderService = Substitute.For<IFileProviderService>();
|
||||
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
|
||||
_mockServiceProvider.GetService(typeof(IFileProviderService)).Returns(_mockFileProviderService);
|
||||
_mockServiceProvider.GetService(typeof(IDirectoryProviderService)).Returns(_mockDirectoryProviderService);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
// Default stubs that keep the happy path working, overridden per test where needed.
|
||||
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
_mockFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
|
||||
_mockFileProviderService.GetSize(Arg.Any<FileSystemPathId>()).Returns(Result.From<long?>(0));
|
||||
_mockFileProviderService.GetLastWriteTime(Arg.Any<FileSystemPathId>()).Returns(Result.From(Optional<DateTime>.None()));
|
||||
_mockDirectoryProviderService.GetLastWriteTime(Arg.Any<FileSystemPathId>()).Returns(Result.From(Optional<DateTime>.None()));
|
||||
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_sut = new MusicFileSystemDiscoveryJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve the library"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), 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);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheLibraryHasAudioFiles_ShouldStageOnlyTheAudioFilesAndComplete()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH, IMAGE_FILE_PATH], subdirectories: []);
|
||||
_mockFileProviderService.GetSize(Arg.Is<FileSystemPathId>(path => path.Path == AUDIO_FILE_PATH)).Returns(Result.From<long?>(1234L));
|
||||
_mockFileProviderService.GetLastWriteTime(Arg.Is<FileSystemPathId>(path => path.Path == AUDIO_FILE_PATH))
|
||||
.Returns(Result.From(Optional<DateTime>.Some(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc))));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1
|
||||
&& entities.First().Path == AUDIO_FILE_PATH
|
||||
&& entities.First().Size == 1234
|
||||
&& entities.First().LibraryScanId == _scanId.Value
|
||||
&& entities.First().NeedsRehash),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheSubdirectoryHasAudioFiles_ShouldTraverseIntoIt()
|
||||
{
|
||||
// Arrange
|
||||
const string SUBDIRECTORY_PATH = @"C:\Music\Album";
|
||||
SetupLibrary();
|
||||
SetupDirectory(ROOT_PATH, files: [], subdirectories: [SUBDIRECTORY_PATH]);
|
||||
SetupDirectory(SUBDIRECTORY_PATH, files: [AUDIO_FILE_PATH], subdirectories: []);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1 && entities.First().Path == AUDIO_FILE_PATH),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheFastSkipIsEnabledAndTheDirectoryIsUnchanged_ShouldSkipIt()
|
||||
{
|
||||
// Arrange
|
||||
DateTime lastWriteTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true);
|
||||
_mockDirectoryProviderService.GetLastWriteTime(Arg.Is<FileSystemPathId>(path => path.Path == ROOT_PATH))
|
||||
.Returns(Result.From(Optional<DateTime>.Some(lastWriteTime)));
|
||||
_mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>
|
||||
{
|
||||
[ROOT_PATH] = _fingerprintFixture.Create(libraryId: _libraryId.Value, path: ROOT_PATH, lastWriteTimeUtc: lastWriteTime)
|
||||
}));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
_mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any<FileSystemPathId>(), true);
|
||||
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
|
||||
await _mockFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheFastSkipIsEnabledAndTheDirectoryChanged_ShouldStoreAFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
DateTime lastWriteTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true);
|
||||
_mockDirectoryProviderService.GetLastWriteTime(Arg.Is<FileSystemPathId>(path => path.Path == ROOT_PATH))
|
||||
.Returns(Result.From(Optional<DateTime>.Some(lastWriteTime)));
|
||||
_mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>
|
||||
{
|
||||
[ROOT_PATH] = _fingerprintFixture.Create(libraryId: _libraryId.Value, path: ROOT_PATH, lastWriteTimeUtc: lastWriteTime.AddDays(-1))
|
||||
}));
|
||||
SetupDirectory(ROOT_PATH, files: [], subdirectories: []);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockFingerprintRepository.Received(1).UpsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(fingerprints => fingerprints.Count == 1 && fingerprints.First().Path == ROOT_PATH),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheFileSizeAndLastWriteTimeCannotBeRead_ShouldStageTheFileWithDefaults()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []);
|
||||
_mockFileProviderService.GetSize(Arg.Any<FileSystemPathId>()).Returns(Error.Failure("FileSystem.Error", "Failed to read the size"));
|
||||
_mockFileProviderService.GetLastWriteTime(Arg.Any<FileSystemPathId>()).Returns(Error.Failure("FileSystem.Error", "Failed to read the last write time"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1 && entities.First().Size == 0 && entities.First().Ticks == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenReadingTheDirectoryFails_ShouldSkipItAndComplete()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true).Returns(Error.Failure("FileSystem.Error", "Failed to read the files"));
|
||||
_mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Any<FileSystemPathId>(), true).Returns(Error.Failure("FileSystem.Error", "Failed to read the subdirectories"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheStagingInsertFails_ShouldMarkJobAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []);
|
||||
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to stage the discovered files"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheFingerprintUpsertFails_ShouldMarkJobAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true);
|
||||
SetupDirectory(ROOT_PATH, files: [], subdirectories: []);
|
||||
_mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>()));
|
||||
_mockFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to store the fingerprints"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheJobIsCompleted_ShouldPublishProgressAndCallTheChildren()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupDirectory(ROOT_PATH, files: [], subdirectories: []);
|
||||
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
|
||||
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
_sut.AddChild(mockChild);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received().PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the media library reader with a library whose single content location is the test root path.
|
||||
/// </summary>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether the library skips the directories that have not changed since the last scan.</param>
|
||||
private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false)
|
||||
{
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Music,
|
||||
contentLocations: [ROOT_PATH],
|
||||
shouldSkipUnchangedDirectoriesDuringScan: shouldSkipUnchangedDirectoriesDuringScan);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the file and directory providers for the provided directory.
|
||||
/// </summary>
|
||||
/// <param name="directory">The file system path of the directory.</param>
|
||||
/// <param name="files">The file system paths of the files of the directory.</param>
|
||||
/// <param name="subdirectories">The file system paths of the subdirectories of the directory.</param>
|
||||
private void SetupDirectory(string directory, string[] files, string[] subdirectories)
|
||||
{
|
||||
_mockFileProviderService.GetFilePaths(Arg.Is<FileSystemPathId>(path => path.Path == directory), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([.. files.Select(file => PathId(file))]));
|
||||
_mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Is<FileSystemPathId>(path => path.Path == directory), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([.. subdirectories.Select(subdirectoryPath => PathId(subdirectoryPath))]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a file system path id for the provided path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path to create the id for.</param>
|
||||
/// <returns>The created file system path id.</returns>
|
||||
private static FileSystemPathId PathId(string path)
|
||||
{
|
||||
return FileSystemPathId.Create(path).Value;
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicLibraryPathStructure"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicLibraryPathStructureTests
|
||||
{
|
||||
private const string ALBUM_DIRECTORY = @"C:\Music\Queen\A Night at the Opera";
|
||||
private const string TRACK_PATH = @"C:\Music\Queen\A Night at the Opera\Bohemian Rhapsody.flac";
|
||||
|
||||
[Fact]
|
||||
public void GetAlbumDirectory_WhenTheTrackIsInTheAlbumDirectory_ShouldReturnTheTrackDirectory()
|
||||
{
|
||||
// Act
|
||||
string result = MusicLibraryPathStructure.GetAlbumDirectory(TRACK_PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ALBUM_DIRECTORY, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Disc 1")] // canonical disc directory name
|
||||
[InlineData("disc 2")] // lowercase disc directory name
|
||||
[InlineData("CD3")] // compact disc directory name
|
||||
[InlineData("disk4")] // disk directory name
|
||||
public void GetAlbumDirectory_WhenTheTrackIsInADiscDirectory_ShouldReturnTheParentAlbumDirectory(string discDirectoryName)
|
||||
{
|
||||
// Arrange
|
||||
string trackPath = $@"{ALBUM_DIRECTORY}\{discDirectoryName}\Bohemian Rhapsody.flac";
|
||||
|
||||
// Act
|
||||
string result = MusicLibraryPathStructure.GetAlbumDirectory(trackPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(ALBUM_DIRECTORY, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAlbumDirectory_WhenTheDirectoryIsNotADiscDirectory_ShouldReturnTheTrackDirectory()
|
||||
{
|
||||
// Arrange
|
||||
const string NON_DISC_TRACK_PATH = @"C:\Music\Queen\Live\Bohemian Rhapsody.flac";
|
||||
|
||||
// Act
|
||||
string result = MusicLibraryPathStructure.GetAlbumDirectory(NON_DISC_TRACK_PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(@"C:\Music\Queen\Live", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAlbumDirectory_WhenThePathIsNullOrEmpty_ShouldReturnTheProvidedPath()
|
||||
{
|
||||
// Act
|
||||
string nullResult = MusicLibraryPathStructure.GetAlbumDirectory(null!);
|
||||
string emptyResult = MusicLibraryPathStructure.GetAlbumDirectory(string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Null(nullResult);
|
||||
Assert.Equal(string.Empty, emptyResult);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAlbumDirectory_WhenThePathHasNoDirectory_ShouldReturnTheProvidedPath()
|
||||
{
|
||||
// Arrange
|
||||
const string FILE_NAME_ONLY = "Bohemian Rhapsody.flac";
|
||||
|
||||
// Act
|
||||
string result = MusicLibraryPathStructure.GetAlbumDirectory(FILE_NAME_ONLY);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(FILE_NAME_ONLY, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsAReleaseType_ShouldReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
const string RELEASE_TYPE_TRACK_PATH = @"C:\Music\Queen\Album\A Night at the Opera\Bohemian Rhapsody.flac";
|
||||
|
||||
// Act
|
||||
string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(RELEASE_TYPE_TRACK_PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Album", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetReleaseTypeDirectoryName_WhenTheReleaseTypeDirectoryIsLowercase_ShouldReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
const string LOWERCASE_RELEASE_TYPE_TRACK_PATH = @"C:\Music\Queen\album\A Night at the Opera\Bohemian Rhapsody.flac";
|
||||
|
||||
// Act
|
||||
string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(LOWERCASE_RELEASE_TYPE_TRACK_PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("album", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetReleaseTypeDirectoryName_WhenTheAlbumIsMultiDisc_ShouldReturnTheReleaseTypeDirectory()
|
||||
{
|
||||
// Arrange
|
||||
const string MULTI_DISC_TRACK_PATH = @"C:\Music\Queen\Album\A Night at the Opera\Disc 1\Bohemian Rhapsody.flac";
|
||||
|
||||
// Act
|
||||
string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(MULTI_DISC_TRACK_PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Album", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsNotAReleaseType_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
const string NON_RELEASE_TYPE_TRACK_PATH = @"C:\Music\Queen\A Night at the Opera\Bohemian Rhapsody.flac";
|
||||
|
||||
// Act
|
||||
string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(NON_RELEASE_TYPE_TRACK_PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicMediaLibraryScanItemMaterializer"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicMediaLibraryScanItemMaterializerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtistRepository _mockArtistRepository;
|
||||
private readonly IAlbumRepository _mockAlbumRepository;
|
||||
private readonly ITrackRepository _mockTrackRepository;
|
||||
private readonly IMusicLibraryScanItemMetadataRepository _mockStagedMetadataRepository;
|
||||
private readonly MusicMediaLibraryScanItemMaterializer _sut;
|
||||
private readonly MusicLibraryScanItemMetadataEntityFixture _stagedMetadataEntityFixture = new();
|
||||
private readonly List<ArtistEntity> _insertedArtists = [];
|
||||
private readonly Guid _libraryId = Guid.NewGuid();
|
||||
private readonly Guid _scanId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicMediaLibraryScanItemMaterializerTests"/> class.
|
||||
/// </summary>
|
||||
public MusicMediaLibraryScanItemMaterializerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockArtistRepository = Substitute.For<IArtistRepository>();
|
||||
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
|
||||
_mockTrackRepository = Substitute.For<ITrackRepository>();
|
||||
_mockStagedMetadataRepository = Substitute.For<IMusicLibraryScanItemMetadataRepository>();
|
||||
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
|
||||
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
|
||||
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
|
||||
_mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockStagedMetadataRepository);
|
||||
|
||||
_mockArtistRepository.GetByNameAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(null));
|
||||
_mockAlbumRepository.GetByTitleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<AlbumEntity?>(null));
|
||||
_mockArtistRepository.InsertAsync(Arg.Do<ArtistEntity>(artist => _insertedArtists.Add(artist)), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new Created()));
|
||||
_mockAlbumRepository.InsertAsync(Arg.Any<AlbumEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new Created()));
|
||||
_mockTrackRepository.InsertAsync(Arg.Any<TrackEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new Created()));
|
||||
_mockTrackRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>([]));
|
||||
_mockStagedMetadataRepository.DeleteByScanIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new Deleted()));
|
||||
|
||||
_sut = new MusicMediaLibraryScanItemMaterializer();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenTheTracksLiveInDifferentDirectories_ShouldMaterializeOneAlbumPerDirectory()
|
||||
{
|
||||
// Arrange
|
||||
Guid releaseArtistId = Guid.NewGuid();
|
||||
Guid firstReleaseId = Guid.NewGuid();
|
||||
Guid secondReleaseId = Guid.NewGuid();
|
||||
Guid firstRecordingId = Guid.NewGuid();
|
||||
Guid secondRecordingId = Guid.NewGuid();
|
||||
MusicLibraryScanItemMetadataEntity firstStagedItem = _stagedMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Shared Artist Name",
|
||||
releaseName: "Shared Release Title",
|
||||
path: "/music/shared-artist/release-one/first.mp3",
|
||||
musicBrainzArtistId: Guid.NewGuid(),
|
||||
musicBrainzReleaseArtistId: releaseArtistId,
|
||||
musicBrainzReleaseId: firstReleaseId,
|
||||
musicBrainzRecordingId: firstRecordingId);
|
||||
MusicLibraryScanItemMetadataEntity secondStagedItem = _stagedMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Shared Artist Name",
|
||||
releaseName: "Shared Release Title",
|
||||
path: "/music/shared-artist/release-two/second.mp3",
|
||||
musicBrainzArtistId: Guid.NewGuid(),
|
||||
musicBrainzReleaseArtistId: releaseArtistId,
|
||||
musicBrainzReleaseId: secondReleaseId,
|
||||
musicBrainzRecordingId: secondRecordingId);
|
||||
_mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
// The same artist name groups the items under a single artist, whose identifier is the one of the release artist.
|
||||
ArtistEntity artist = Assert.Single(_insertedArtists);
|
||||
Assert.Equal(releaseArtistId, artist.MusicBrainzArtistId);
|
||||
// The distinct release identifiers keep the identically titled releases apart.
|
||||
Assert.Equal(2, artist.Albums.Count);
|
||||
AlbumEntity firstAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == firstReleaseId);
|
||||
AlbumEntity secondAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == secondReleaseId);
|
||||
Assert.Equal(firstRecordingId, Assert.Single(firstAlbum.Tracks).MusicBrainzRecordingId);
|
||||
Assert.Equal(secondRecordingId, Assert.Single(secondAlbum.Tracks).MusicBrainzRecordingId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenCompilationTracksHaveDifferentTrackArtists_ShouldMaterializeASingleAlbumArtist()
|
||||
{
|
||||
// Arrange
|
||||
Guid variousArtistsId = Guid.NewGuid();
|
||||
Guid compilationReleaseId = Guid.NewGuid();
|
||||
MusicLibraryScanItemMetadataEntity firstStagedItem = _stagedMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Various Artists",
|
||||
releaseName: "Now That Is Music",
|
||||
path: "/music/various-artists/now-that-is-music/first.mp3",
|
||||
musicBrainzArtistId: Guid.NewGuid(),
|
||||
musicBrainzReleaseArtistId: variousArtistsId,
|
||||
musicBrainzReleaseId: compilationReleaseId);
|
||||
MusicLibraryScanItemMetadataEntity secondStagedItem = _stagedMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Various Artists",
|
||||
releaseName: "Now That Is Music",
|
||||
path: "/music/various-artists/now-that-is-music/second.mp3",
|
||||
musicBrainzArtistId: Guid.NewGuid(),
|
||||
musicBrainzReleaseArtistId: variousArtistsId,
|
||||
musicBrainzReleaseId: compilationReleaseId);
|
||||
_mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
// The different track artists of the compilation do not split the release artist into several identically named artists.
|
||||
ArtistEntity artist = Assert.Single(_insertedArtists);
|
||||
Assert.Equal("Various Artists", artist.Name);
|
||||
Assert.Equal(variousArtistsId, artist.MusicBrainzArtistId);
|
||||
AlbumEntity album = Assert.Single(artist.Albums);
|
||||
Assert.Equal(2, album.Tracks.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenTheTagsDoNotCarryMusicBrainzIds_ShouldGroupByTheNameAndTitle()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryScanItemMetadataEntity firstStagedItem = _stagedMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Shared Artist Name",
|
||||
releaseName: "Shared Release Title",
|
||||
path: "/music/shared-artist/shared-release/first.mp3",
|
||||
includeMusicBrainzTags: false);
|
||||
MusicLibraryScanItemMetadataEntity secondStagedItem = _stagedMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Shared Artist Name",
|
||||
releaseName: "Shared Release Title",
|
||||
path: "/music/shared-artist/shared-release/second.mp3",
|
||||
includeMusicBrainzTags: false);
|
||||
_mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
// Without identifiers, the items fall back to the name and the title, so they collapse into a single artist with a single album.
|
||||
ArtistEntity artist = Assert.Single(_insertedArtists);
|
||||
AlbumEntity album = Assert.Single(artist.Albums);
|
||||
Assert.Null(artist.MusicBrainzArtistId);
|
||||
Assert.Null(album.MusicBrainzReleaseId);
|
||||
Assert.Equal(2, album.Tracks.Count);
|
||||
}
|
||||
}
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
|
||||
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 Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicMetadataExtractionJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicMetadataExtractionJobTests
|
||||
{
|
||||
private const string ROOT_PATH = @"C:\Music";
|
||||
private const string AUDIO_FILE_PATH = @"C:\Music\Queen\Bohemian Rhapsody.mp3";
|
||||
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMusicLibraryScanItemMetadataRepository _mockMusicMetadataRepository;
|
||||
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
|
||||
private readonly ILibraryPathTemplateService _mockPathTemplateService;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MusicMetadataExtractionJob _sut;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
|
||||
private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryId _libraryId;
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicMetadataExtractionJobTests"/> class.
|
||||
/// </summary>
|
||||
public MusicMetadataExtractionJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMusicMetadataRepository = Substitute.For<IMusicLibraryScanItemMetadataRepository>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicMetadataRepository);
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockPathTemplateService = Substitute.For<ILibraryPathTemplateService>();
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
_mockServiceProvider.GetService(typeof(ILibraryPathTemplateService)).Returns(_mockPathTemplateService);
|
||||
_mockServiceProvider.GetService(typeof(IPathService)).Returns(_mockPathService);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
// Default stubs that keep the happy path working, overridden per test where needed.
|
||||
_mockMusicMetadataRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
_mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(_libraryPathTemplateFixture.Create()));
|
||||
_mockPathTemplateService.Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), Arg.Any<string>(), Arg.Any<char>()).Returns(Result.From<Optional<ParsedLibraryPath>>(Optional<ParsedLibraryPath>.None()));
|
||||
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(true);
|
||||
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_sut = new MusicMetadataExtractionJob(_mockServiceScopeFactory, Substitute.For<Microsoft.Extensions.Logging.ILogger<MusicMetadataExtractionJob>>())
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to retrieve the library"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockMusicMetadataRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), 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);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThereArePathsToProcess_ShouldStageTheirMetadataAndComplete()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupPaths(AUDIO_FILE_PATH);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
|
||||
&& items.First().Path == AUDIO_FILE_PATH
|
||||
&& items.First().LibraryScanId == _scanId.Value
|
||||
&& items.First().LibraryId == _libraryId.Value
|
||||
&& items.First().TrackTitle == "Bohemian Rhapsody"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThePathMatchesTheTemplate_ShouldApplyThePathDerivedMetadata()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupPaths(AUDIO_FILE_PATH);
|
||||
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
|
||||
{
|
||||
[LibraryPathPartKind.Artist] = "Queen",
|
||||
[LibraryPathPartKind.ReleaseType] = "Album",
|
||||
[LibraryPathPartKind.ReleaseYear] = "1975",
|
||||
[LibraryPathPartKind.ReleaseName] = "A Night at the Opera",
|
||||
[LibraryPathPartKind.TrackNumber] = "11",
|
||||
[LibraryPathPartKind.DiscNumber] = "1",
|
||||
[LibraryPathPartKind.TrackName] = "Bohemian Rhapsody"
|
||||
});
|
||||
_mockPathTemplateService.Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), Arg.Any<string>(), Arg.Any<char>())
|
||||
.Returns(Result.From<Optional<ParsedLibraryPath>>(Optional<ParsedLibraryPath>.Some(parsedPath)));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
|
||||
&& items.First().ArtistName == "Queen"
|
||||
&& items.First().ReleaseType == MusicReleaseType.Album
|
||||
&& items.First().ReleaseYear == 1975
|
||||
&& items.First().ReleaseName == "A Night at the Opera"
|
||||
&& items.First().TrackNumber == 11
|
||||
&& items.First().DiscNumber == 1
|
||||
&& items.First().TrackTitle == "Bohemian Rhapsody"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheStagingInsertFails_ShouldMarkJobAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupPaths(AUDIO_FILE_PATH);
|
||||
_mockMusicMetadataRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to stage the extracted metadata"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheJobIsCompleted_ShouldPublishProgressAndCallTheChildren()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupPaths(AUDIO_FILE_PATH);
|
||||
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
|
||||
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
_sut.AddChild(mockChild);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received().PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the media library reader with a library whose single content location is the test root path.
|
||||
/// </summary>
|
||||
private void SetupLibrary()
|
||||
{
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Music,
|
||||
contentLocations: [ROOT_PATH]);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the staging results repository with the paths that need their metadata extracted.
|
||||
/// </summary>
|
||||
/// <param name="paths">The file system paths that need their metadata extracted.</param>
|
||||
private void SetupPaths(params string[] paths)
|
||||
{
|
||||
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(paths));
|
||||
}
|
||||
}
|
||||
+25
-648
@@ -1,26 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
@@ -31,18 +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.MediaContributors;
|
||||
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
|
||||
@@ -59,21 +36,13 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IMediaContributorRepository _mockMediaContributorRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMediaLibraryScanMetadataEnricher _mockMetadataEnricher;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<MediaLibraryScanMetadataEnrichmentJob> _mockLogger;
|
||||
private readonly MediaLibraryScanMetadataEnrichmentJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
|
||||
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
@@ -91,25 +60,27 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
// The job resolves the metadata enricher of the loaded library type from the service scope, so the music enricher must be available.
|
||||
_mockMetadataEnricher = Substitute.For<IMediaLibraryScanMetadataEnricher>();
|
||||
_mockMetadataEnricher.SupportedLibraryType.Returns(LibraryType.Music);
|
||||
_mockMetadataEnricher.EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanMetadataEnricher>))
|
||||
.Returns(new IMediaLibraryScanMetadataEnricher[] { _mockMetadataEnricher });
|
||||
|
||||
_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<MediaLibraryScanMetadataEnrichmentJob>>();
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanMetadataEnrichmentJob(_mockServiceScopeFactory, _mockLogger)
|
||||
_sut = new MediaLibraryScanMetadataEnrichmentJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
@@ -118,633 +89,39 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoBooksNeedEnrichment_ShouldCompleteAndPublishFinishedEvent()
|
||||
public async Task ExecuteAsync_WhenEnrichmentSucceeds_ShouldPublishProgressChangedEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(0));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
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
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipEnrichmentWithoutMarkingBooksAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// a library without metadata providers must not mark its books as failed to enrich, so the book repositories are not touched
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenABookPageIsProcessed_ShouldDetachTheTrackedEntitiesAfterSaving()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the tracked entities of the page are detached after saving, so that the peak memory stays bounded regardless of the library size
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
_mockUnitOfWork.Received(1).ClearTrackedEntities();
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the metadata provider configurations"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
await _mockMetadataEnricher.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>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAggregateMetadataIsEnabled_ShouldFeedTheEarlierProvidersFindingsToTheLaterOnes()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid secondPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
IMetadataProvider secondProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", openLibraryId: "OL123", description: "First Description"));
|
||||
secondProvider.Name.Returns("Second Provider");
|
||||
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
secondProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
// the book has no known identifiers of its own, so the findings of the first provider are fed to the second one
|
||||
book.OpenLibraryId = null;
|
||||
SetupSingleBookPage(book, firstPluginId, secondPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the second provider receives the lookup enriched with the open library Id discovered by the first provider
|
||||
await secondProvider.Received(1).GetMetadataAsync(
|
||||
Arg.Is<MetadataLookupDto>(lookup => lookup is BookMetadataLookupDto && ((BookMetadataLookupDto)lookup).OpenLibraryId == "OL123"),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAggregateMetadataIsDisabled_ShouldOnlyApplyTheFirstUsableProviderMetadata()
|
||||
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid secondPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
IMetadataProvider secondProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher"));
|
||||
secondProvider.Name.Returns("Second Provider");
|
||||
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
secondProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId, secondPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the second provider is not queried when the aggregation is disabled and the first provider returned usable metadata
|
||||
await secondProvider.DidNotReceive().GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookAsFailedToEnrich()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(includeTitle: false));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the enrichment state is tracked directly on the entity, so the failed status is visible on the same instance
|
||||
Assert.Equal(MetadataStatus.Failed, book.MetadataStatus);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMetadataIsEnriched_ShouldSetTheEnrichmentTrackingColumnsOnTheEntity()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the enrichment tracking columns are managed directly on the entity by the enrichment job
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal("First Provider", book.MetadataProvider);
|
||||
Assert.NotNull(book.LastMetadataUpdateUtc);
|
||||
Assert.Equal("First Title", book.Title);
|
||||
Assert.Equal("First Publisher", book.Publisher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMetadataHasContributors_ShouldFindOrCreateThemAndLinkThemToTheBook()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author);
|
||||
MediaContributorDto translator = _mediaContributorDtoFixture.Create(displayName: "Jane Translator", role: MediaContributorRole.Translator);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author, translator]));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
MediaContributorEntity translatorEntity = _mediaContributorEntityFixture.Create(displayName: "Jane Translator");
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(authorEntity));
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(translatorEntity));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
|
||||
// the participation rows are replaced on the entity, carrying the canonical role of each contributor
|
||||
Assert.Equal(2, book.Contributors.Count);
|
||||
BookContributorEntity linkedAuthor = Assert.Single(book.Contributors, contributor => contributor.MediaContributorId == authorEntity.Id);
|
||||
Assert.Equal(MediaContributorRole.Author, linkedAuthor.Role);
|
||||
Assert.Equal(book.Id, linkedAuthor.BookId);
|
||||
BookContributorEntity linkedTranslator = Assert.Single(book.Contributors, contributor => contributor.MediaContributorId == translatorEntity.Id);
|
||||
Assert.Equal(MediaContributorRole.Translator, linkedTranslator.Role);
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheSameContributorAppearsInMultipleBooksOfAPage_ShouldFindOrCreateItOnlyOnce()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author]));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
|
||||
BookEntity firstBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/a.epub");
|
||||
BookEntity secondBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/b.epub");
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)]));
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(2));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([firstBook, secondBook]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(authorEntity));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the contributor cache of the page guarantees a single contributor per person, so the repository is queried only once
|
||||
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
Assert.Single(firstBook.Contributors);
|
||||
Assert.Single(secondBook.Contributors);
|
||||
Assert.Equal(authorEntity.Id, firstBook.Contributors[0].MediaContributorId);
|
||||
Assert.Equal(authorEntity.Id, secondBook.Contributors[0].MediaContributorId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseMetadataProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
Guid localPluginId = Guid.NewGuid();
|
||||
Guid webPluginId = Guid.NewGuid();
|
||||
IMetadataProvider localProvider = Substitute.For<IMetadataProvider>();
|
||||
localProvider.Name.Returns("Local Provider");
|
||||
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
localProvider.RequiresWebAccess.Returns(false);
|
||||
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(includeTitle: false));
|
||||
IMetadataProvider webProvider = Substitute.For<IMetadataProvider>();
|
||||
webProvider.Name.Returns("Web Provider");
|
||||
webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
webProvider.RequiresWebAccess.Returns(true);
|
||||
webProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Web Title"));
|
||||
|
||||
SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, localPluginId, webPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the local provider is used, but the provider requiring access to the web is skipped, so the book cannot be enriched
|
||||
await localProvider.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
await webProvider.DidNotReceive().GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheLibraryPermitsWebDownloads_ShouldUseMetadataProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
Guid localPluginId = Guid.NewGuid();
|
||||
Guid webPluginId = Guid.NewGuid();
|
||||
IMetadataProvider localProvider = Substitute.For<IMetadataProvider>();
|
||||
localProvider.Name.Returns("Local Provider");
|
||||
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
localProvider.RequiresWebAccess.Returns(false);
|
||||
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(includeTitle: false));
|
||||
IMetadataProvider webProvider = Substitute.For<IMetadataProvider>();
|
||||
webProvider.Name.Returns("Web Provider");
|
||||
webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
webProvider.RequiresWebAccess.Returns(true);
|
||||
webProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Web Title"));
|
||||
|
||||
SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: true)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, localPluginId, webPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the provider requiring access to the web is used when the library permits downloading data from the web
|
||||
await webProvider.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCountingTheBooksNeedingMetadataFails_ShouldMarkJobAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)]));
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to count the books to enrich"));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(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_WhenGettingTheBooksPageNeedingMetadataFails_ShouldMarkJobAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)]));
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the books to enrich"));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAMetadataProviderThrowsWhileTryingTheProvidersInOrder_ShouldTryTheNextProvider()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid secondPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<MetadataDto?>(new InvalidOperationException("The metadata provider failed")));
|
||||
IMetadataProvider secondProvider = Substitute.For<IMetadataProvider>();
|
||||
secondProvider.Name.Returns("Second Provider");
|
||||
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
secondProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId, secondPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// a failing metadata provider must not prevent the metadata of the next provider from being used
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal("Second Provider", book.MetadataProvider);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAMetadataProviderThrowsWhileAggregatingMetadata_ShouldUseTheFindingsOfTheOtherProviders()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid secondPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<MetadataDto?>(new InvalidOperationException("The metadata provider failed")));
|
||||
IMetadataProvider secondProvider = Substitute.For<IMetadataProvider>();
|
||||
secondProvider.Name.Returns("Second Provider");
|
||||
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
secondProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher"));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId, secondPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal("Second Provider", book.MetadataProvider);
|
||||
Assert.Equal("Second Title", book.Title);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAContributorHasNoDisplayName_ShouldSkipLinkingIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
MediaContributorDto namelessContributor = _mediaContributorDtoFixture.Create(role: MediaContributorRole.Author) with { Name = null };
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [namelessContributor]));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// a contributor without a display name cannot be linked to the book, so no contributor is queried or created
|
||||
await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
Assert.Empty(book.Contributors);
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAContributorHasNoRole_ShouldLinkItWithTheDefaultRole()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
MediaContributorDto contributorWithoutRole = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert") with { Role = null };
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [contributorWithoutRole]));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", includeMetadata: false);
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(authorEntity));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// a contributor without a role is linked with the default canonical role
|
||||
BookContributorEntity linkedContributor = Assert.Single(book.Contributors);
|
||||
Assert.Equal(MediaContributorRole.Author, linkedContributor.Role);
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFindingOrCreatingAContributorFails_ShouldMarkJobAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author]));
|
||||
|
||||
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, firstPluginId);
|
||||
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to find or create the contributor"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload()
|
||||
{
|
||||
// Arrange
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(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 metadata providers, so that the job resolves them from the dependency injection container.
|
||||
/// </summary>
|
||||
/// <param name="firstPluginId">The Id of the plugin providing the first metadata provider.</param>
|
||||
/// <param name="firstProvider">The first metadata provider to resolve.</param>
|
||||
/// <param name="secondPluginId">The Id of the plugin providing the second metadata provider, if any.</param>
|
||||
/// <param name="secondProvider">The second metadata provider to resolve, if any.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the user settings enable aggregating metadata from multiple providers when fields are missing.</param>
|
||||
private void SetupRealServiceProviderForProviders(Guid firstPluginId, IMetadataProvider firstProvider, Guid? secondPluginId = null, IMetadataProvider? secondProvider = null, bool shouldAggregateMetadataWhenMissing = false)
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(firstPluginId, firstProvider);
|
||||
if (secondPluginId is not null && secondProvider is not null)
|
||||
services.AddKeyedSingleton(secondPluginId.Value, secondProvider);
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
|
||||
ServiceProvider realServiceProvider = services.BuildServiceProvider();
|
||||
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
|
||||
|
||||
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the repositories so that the job processes a single page containing the given book, configured with the given metadata providers.
|
||||
/// </summary>
|
||||
/// <param name="book">The book the job must enrich.</param>
|
||||
/// <param name="configuredPluginIds">The Ids of the plugins configured as metadata providers for the library.</param>
|
||||
private void SetupSingleBookPage(BookEntity book, params Guid[] configuredPluginIds)
|
||||
{
|
||||
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>(
|
||||
configuredPluginIds.Select((pluginId, index) => _configurationEntityFixture.Create(_libraryId.Value, pluginId, index + 1)).ToList()));
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
await _mockMetadataEnricher.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>());
|
||||
}
|
||||
}
|
||||
+37
-11
@@ -12,9 +12,11 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
|
||||
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;
|
||||
@@ -22,6 +24,7 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContex
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
@@ -83,6 +86,9 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
// The job resolves the materializer of the loaded library type from the service scope, so the books materializer must be available.
|
||||
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanItemMaterializer>))
|
||||
.Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(Substitute.For<ILibraryPathTemplateService>(), Substitute.For<IPathService>()) });
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
@@ -113,7 +119,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// a missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted
|
||||
// A missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted.
|
||||
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
@@ -121,6 +127,24 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFingerprintsArePersisted_ShouldPublishProgressChangedEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
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_WhenMetadataFingerprintDiffers_ShouldResetTheMetadataStatus()
|
||||
{
|
||||
@@ -134,7 +158,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job
|
||||
// The metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job.
|
||||
await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
@@ -155,7 +179,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job
|
||||
// The artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job.
|
||||
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
@@ -172,9 +196,9 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
List<LibraryArtworkProviderConfigurationEntity> artworkConfigurations = _artworkConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1);
|
||||
SetupLibraryAndConfigurations(library, metadataConfigurations, artworkConfigurations);
|
||||
|
||||
// the stored fingerprints match the ones computed from the current provider configuration
|
||||
// The stored fingerprints match the ones computed from the current provider configuration.
|
||||
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(metadataConfigurations, false, library.CanDownloadMetadataFromWeb);
|
||||
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, library.CanDownloadMetadataFromWeb);
|
||||
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, false, library.CanDownloadMetadataFromWeb);
|
||||
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
|
||||
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
|
||||
|
||||
@@ -182,7 +206,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted
|
||||
// The configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted.
|
||||
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
@@ -194,7 +218,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
public async Task ExecuteAsync_WhenBothFingerprintsDiffer_ShouldPersistTheUpdatedFingerprintsViaSaveChangesOnly()
|
||||
{
|
||||
// Arrange
|
||||
// both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity
|
||||
// Both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity.
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: "STALE_ARTWORK");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
@@ -206,8 +230,8 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and
|
||||
// flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run
|
||||
// Regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and
|
||||
// flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run.
|
||||
await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
@@ -359,7 +383,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// reading the user settings is best effort, a failure must not prevent the fingerprints from being persisted
|
||||
// Reading the user settings is best effort, a failure must not prevent the fingerprints from being persisted.
|
||||
Assert.NotNull(library.MetadataProvidersConfigurationFingerprint);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
@@ -377,7 +401,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the user settings repository is optional, its absence must not prevent the fingerprints from being persisted
|
||||
// The user settings repository is optional, its absence must not prevent the fingerprints from being persisted.
|
||||
Assert.NotNull(library.MetadataProvidersConfigurationFingerprint);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
@@ -413,6 +437,8 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
/// <param name="artworkConfigurations">The artwork provider configurations of the media library.</param>
|
||||
private void SetupLibraryAndConfigurations(LibraryEntity library, List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
|
||||
{
|
||||
// The job resolves the materializer by the library type, so the fixture-provided library must be of the type the books materializer supports.
|
||||
library.LibraryType = LibraryType.Book;
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
SetupConfigurations(metadataConfigurations, artworkConfigurations);
|
||||
|
||||
+57
-13
@@ -1,22 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
|
||||
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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
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.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
@@ -39,6 +44,7 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly ILibraryScanSnapshotRepository _mockSnapshotRepository;
|
||||
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
@@ -47,6 +53,7 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
@@ -64,13 +71,23 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockSnapshotRepository = Substitute.For<ILibraryScanSnapshotRepository>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockSnapshotRepository);
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
// By default no book exists yet, so every scanned path is materialized; the tests that need existing books override this.
|
||||
_mockBookRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>([]));
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
// The job resolves the materializer of the loaded library type from the service scope, so the books materializer must be available.
|
||||
ILibraryPathTemplateService mockPathTemplateService = Substitute.For<ILibraryPathTemplateService>();
|
||||
mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
|
||||
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanItemMaterializer>))
|
||||
.Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(mockPathTemplateService, Substitute.For<IPathService>()) });
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
@@ -80,6 +97,8 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Book)));
|
||||
_sut = new MediaLibraryScanResultsSaveJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
@@ -102,8 +121,8 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["book1.pdf", "book2.pdf"]));
|
||||
_mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(null));
|
||||
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>([]));
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Created));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
@@ -121,6 +140,31 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenScanResultsAreApplied_ShouldPublishProgressChangedEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
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_WhenNoContentChanged_ShouldNotResetTheEnrichmentState()
|
||||
{
|
||||
@@ -139,7 +183,7 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// no book content changed since the last scan, so the enrichment state of the books must not be reset
|
||||
// No book content changed since the last scan, so the enrichment state of the books must not be reset.
|
||||
await _mockBookRepository.DidNotReceive().ResetEnrichmentStateForPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
@@ -156,8 +200,8 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["existing.pdf"]));
|
||||
_mockBookRepository.GetByPathAsync(_libraryId.Value, "existing.pdf", Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(_bookEntityFixture.Create(path: "existing.pdf")));
|
||||
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>(["existing.pdf"]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
@@ -292,7 +336,7 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingExistingBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
public async Task ExecuteAsync_WhenGettingExistingPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
@@ -303,8 +347,8 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["book1.pdf"]));
|
||||
_mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the existing book"));
|
||||
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the existing paths"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
@@ -329,8 +373,8 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["book1.pdf"]));
|
||||
_mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(null));
|
||||
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>([]));
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to insert the shell book"));
|
||||
|
||||
@@ -385,8 +429,8 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["_.pdf"]));
|
||||
_mockBookRepository.GetByPathAsync(_libraryId.Value, "_.pdf", Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(null));
|
||||
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>([]));
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Created));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
@@ -395,7 +439,7 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the file name is made only of separators, so the derived title is empty and the raw file name is used as a fallback
|
||||
// The file name is made only of separators, so the derived title is empty and the raw file name is used as a fallback.
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "_.pdf" && book.Title == "_"), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ProviderConfigurationFingerprint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ProviderConfigurationFingerprintTests
|
||||
{
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
|
||||
private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ComputeMetadataFingerprint_WhenCalledWithTheSameConfiguration_ShouldReturnTheSameFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
List<LibraryMetadataProviderConfigurationEntity> configurations =
|
||||
[
|
||||
_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0),
|
||||
_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1)
|
||||
];
|
||||
|
||||
// Act
|
||||
string firstFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true);
|
||||
string secondFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstFingerprint, secondFingerprint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputeMetadataFingerprint_WhenOnlyTheOrderOfConfigurationsDiffers_ShouldReturnTheSameFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryMetadataProviderConfigurationEntity first = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0);
|
||||
LibraryMetadataProviderConfigurationEntity second = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1);
|
||||
|
||||
// Act
|
||||
string firstFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([first, second], false, true);
|
||||
string secondFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([second, first], false, true);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstFingerprint, secondFingerprint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputeMetadataFingerprint_WhenAProviderChanges_ShouldReturnADifferentFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
LibraryMetadataProviderConfigurationEntity enabled = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, rank: 0, isEnabled: true);
|
||||
LibraryMetadataProviderConfigurationEntity disabled = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, rank: 0, isEnabled: false);
|
||||
|
||||
// Act
|
||||
string enabledFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([enabled], false, true);
|
||||
string disabledFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([disabled], false, true);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(enabledFingerprint, disabledFingerprint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputeMetadataFingerprint_WhenTheAggregationSettingChanges_ShouldReturnADifferentFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
List<LibraryMetadataProviderConfigurationEntity> configurations = [_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)];
|
||||
|
||||
// Act
|
||||
string withoutAggregation = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true);
|
||||
string withAggregation = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, true, true);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(withoutAggregation, withAggregation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputeMetadataFingerprint_WhenTheWebAccessSettingChanges_ShouldReturnADifferentFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
List<LibraryMetadataProviderConfigurationEntity> configurations = [_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)];
|
||||
|
||||
// Act
|
||||
string withoutWebAccess = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, false);
|
||||
string withWebAccess = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(withoutWebAccess, withWebAccess);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputeArtworkFingerprint_WhenOnlyTheOrderOfConfigurationsDiffers_ShouldReturnTheSameFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryArtworkProviderConfigurationEntity first = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0);
|
||||
LibraryArtworkProviderConfigurationEntity second = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1);
|
||||
|
||||
// Act
|
||||
string firstFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([first, second], false, true);
|
||||
string secondFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([second, first], false, true);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstFingerprint, secondFingerprint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputeArtworkFingerprint_WhenAProviderChanges_ShouldReturnADifferentFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryArtworkProviderConfigurationEntity first = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0);
|
||||
LibraryArtworkProviderConfigurationEntity second = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0);
|
||||
|
||||
// Act
|
||||
string firstFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([first], false, true);
|
||||
string secondFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([second], false, true);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstFingerprint, secondFingerprint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputeArtworkFingerprint_WhenTheAggregationSettingChanges_ShouldReturnADifferentFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
List<LibraryArtworkProviderConfigurationEntity> configurations = [_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)];
|
||||
|
||||
// Act
|
||||
string withoutAggregation = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(configurations, false, true);
|
||||
string withAggregation = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(configurations, true, true);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(withoutAggregation, withAggregation);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputePathTemplateFingerprint_WhenOnlyTheOrderOfPartsDiffers_ShouldReturnTheSameFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplatePartEntity first = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}");
|
||||
LibraryPathTemplatePartEntity second = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.ReleaseName, representation: "{0}");
|
||||
|
||||
// Act
|
||||
string firstFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([first, second]);
|
||||
string secondFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([second, first]);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstFingerprint, secondFingerprint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputePathTemplateFingerprint_WhenAPartChanges_ShouldReturnADifferentFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplatePartEntity artist = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}");
|
||||
LibraryPathTemplatePartEntity releaseName = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.ReleaseName, representation: "{0}");
|
||||
|
||||
// Act
|
||||
string artistFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([artist]);
|
||||
string releaseNameFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([releaseName]);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(artistFingerprint, releaseNameFingerprint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ComputePathTemplateFingerprint_WhenTheOptionalityChanges_ShouldReturnADifferentFingerprint()
|
||||
{
|
||||
// Arrange
|
||||
LibraryPathTemplatePartEntity required = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
|
||||
LibraryPathTemplatePartEntity optional = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true);
|
||||
|
||||
// Act
|
||||
string requiredFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([required]);
|
||||
string optionalFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([optional]);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(requiredFingerprint, optionalFingerprint);
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksMediaLibraryScanItemMaterializer"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BooksMediaLibraryScanItemMaterializerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ILibraryPathTemplateService _mockPathTemplateService;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly BooksMediaLibraryScanItemMaterializer _sut;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly Guid _libraryId;
|
||||
private readonly Guid _scanId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanItemMaterializerTests"/> class.
|
||||
/// </summary>
|
||||
public BooksMediaLibraryScanItemMaterializerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockPathTemplateService = Substitute.For<ILibraryPathTemplateService>();
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_libraryId = Guid.NewGuid();
|
||||
_scanId = Guid.NewGuid();
|
||||
|
||||
// Default stubs: the library has no path template of its own, no book is stored yet, and the separator is the Windows one.
|
||||
_mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>())
|
||||
.Returns(Result.From(LibraryPathTemplate.Empty()));
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
_mockBookRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>([]));
|
||||
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Created));
|
||||
_mockPathTemplateService.Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), Arg.Any<string>(), Arg.Any<char>())
|
||||
.Returns(Result.From(Optional<ParsedLibraryPath>.None()));
|
||||
|
||||
_sut = new BooksMediaLibraryScanItemMaterializer(_mockPathTemplateService, _mockPathService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenPathSharesTheContentLocationPrefixButIsOutside_ShouldFallBackToTheFileNameRelativePath()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockPathService.IsPathWithin("C:\\MusicBackup\\track.epub", "C:\\Music").Returns(false);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, ["C:\\MusicBackup\\track.epub"], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// A sibling directory whose name only starts with the content location name is not inside the library, so the item is not parsed against
|
||||
// the path template, and the file name is used as the relative path instead.
|
||||
Assert.False(result.IsFailure);
|
||||
_mockPathService.Received(1).IsPathWithin("C:\\MusicBackup\\track.epub", "C:\\Music");
|
||||
_mockPathTemplateService.Received(1).Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), "track.epub", '\\');
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenPathIsInsideTheContentLocation_ShouldParseThePathRelativeToTheContentLocation()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockPathService.IsPathWithin("C:\\Music\\Artist\\track.epub", "C:\\Music").Returns(true);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, ["C:\\Music\\Artist\\track.epub"], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockPathService.Received(1).IsPathWithin("C:\\Music\\Artist\\track.epub", "C:\\Music");
|
||||
_mockPathTemplateService.Received(1).Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), "Artist\\track.epub", '\\');
|
||||
}
|
||||
}
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
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.MediaContributors;
|
||||
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.Abstractions;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksMediaLibraryScanMetadataEnricher"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BooksMediaLibraryScanMetadataEnricherTests
|
||||
{
|
||||
private const string PROVIDER_A_NAME = "ProviderA";
|
||||
private const string PROVIDER_B_NAME = "ProviderB";
|
||||
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository;
|
||||
private readonly IUserSettingsRepository _mockUserSettingsRepository;
|
||||
private readonly IMediaContributorRepository _mockMediaContributorRepository;
|
||||
private readonly IMetadataProvider _mockProviderA;
|
||||
private readonly IMetadataProvider _mockProviderB;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ServiceProvider _serviceProvider;
|
||||
private readonly BooksMediaLibraryScanMetadataEnricher _sut;
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _metadataConfigurationEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
|
||||
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanMetadataEnricherTests"/> class.
|
||||
/// </summary>
|
||||
public BooksMediaLibraryScanMetadataEnricherTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository);
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
|
||||
|
||||
_mockProviderA = Substitute.For<IMetadataProvider>();
|
||||
ConfigureProvider(_mockProviderA, PROVIDER_A_NAME);
|
||||
_mockProviderB = Substitute.For<IMetadataProvider>();
|
||||
ConfigureProvider(_mockProviderB, PROVIDER_B_NAME);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
|
||||
// The configured providers are registered under the plugin Ids they are configured with, the way the host registers plugin provided services.
|
||||
Guid pluginAId = Guid.NewGuid();
|
||||
Guid pluginBId = Guid.NewGuid();
|
||||
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>.Success(
|
||||
[
|
||||
_metadataConfigurationEntityFixture.Create(_libraryId.Value, pluginAId, rank: 1),
|
||||
_metadataConfigurationEntityFixture.Create(_libraryId.Value, pluginBId, rank: 2)
|
||||
]));
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddScoped(_ => _mockUnitOfWork);
|
||||
services.AddScoped(_ => _mockDomainEventPublisher);
|
||||
services.AddKeyedTransient(pluginAId, (serviceProvider, serviceKey) => _mockProviderA);
|
||||
services.AddKeyedTransient(pluginBId, (serviceProvider, serviceKey) => _mockProviderB);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
_sut = new BooksMediaLibraryScanMetadataEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), NullLogger<BooksMediaLibraryScanMetadataEnricher>.Instance);
|
||||
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<int>.Success(1));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<IReadOnlyList<BookEntity>>.Success([]));
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<UserSettingsEntity?>.Success(null));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Success));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>.Success([]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheMetadataConfigurationsCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Provider.Error", "Failed to read the configurations"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheFirstProviderReturnsApplicableMetadata_ShouldNotQueryTheFollowingProviders()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableBookMetadata("Dune"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockProviderB.DidNotReceive().GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal(PROVIDER_A_NAME, book.MetadataProvider);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheFirstProviderReturnsNoUsableMetadata_ShouldQueryTheFollowingProviders()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)null);
|
||||
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableBookMetadata("Dune"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal(PROVIDER_B_NAME, book.MetadataProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookFailed()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)null);
|
||||
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)null);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(MetadataStatus.Failed, book.MetadataStatus);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenAggregationIsEnabled_ShouldQueryEveryProviderAndMergeTheirMetadata()
|
||||
{
|
||||
// Arrange
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(_userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<UserSettingsEntity?>.Success(_userSettingsEntityFixture.Create(userId: _userId.Value, shouldAggregateMetadataWhenMissing: true)));
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableBookMetadata("Dune"));
|
||||
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableBookMetadata("Dune Messiah"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
|
||||
Assert.Equal($"{PROVIDER_A_NAME}, {PROVIDER_B_NAME}", book.MetadataProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheMetadataHasContributors_ShouldLinkThemToTheBook()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(contributor));
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableBookMetadata(
|
||||
"Dune",
|
||||
contributors: [_mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author, legalName: null)]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", null, Arg.Any<CancellationToken>());
|
||||
BookContributorEntity linkedContributor = Assert.Single(book.Contributors);
|
||||
Assert.Equal(contributor.Id, linkedContributor.MediaContributorId);
|
||||
Assert.Equal(MediaContributorRole.Author, linkedContributor.Role);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheBookCountCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, 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
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, 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_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableBookMetadata("Dune"));
|
||||
_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 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.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<int>.Success(books.Length));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result<IReadOnlyList<BookEntity>>.Success(books),
|
||||
Result<IReadOnlyList<BookEntity>>.Success([]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the provided substitute metadata provider so that it declares the book lookup type for the books media library type.
|
||||
/// </summary>
|
||||
/// <param name="metadataProvider">The metadata provider substitute to configure.</param>
|
||||
/// <param name="name">The display name the provider reports.</param>
|
||||
private static void ConfigureProvider(IMetadataProvider metadataProvider, string name)
|
||||
{
|
||||
metadataProvider.Name.Returns(name);
|
||||
metadataProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
metadataProvider.RequiresWebAccess.Returns(false);
|
||||
metadataProvider.LookupType.Returns(typeof(BookMetadataLookupDto));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a book metadata that is usable and carries only a title, and optionally a set of contributors.
|
||||
/// </summary>
|
||||
/// <param name="title">The title of the book.</param>
|
||||
/// <param name="contributors">The optional contributors of the book.</param>
|
||||
/// <returns>The created book metadata.</returns>
|
||||
private BookMetadataDto CreateApplicableBookMetadata(string title, List<MediaContributorDto>? contributors = null)
|
||||
{
|
||||
return _bookMetadataDtoFixture.Create(
|
||||
title: title,
|
||||
contributors: contributors);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user