mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 16:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+637
@@ -0,0 +1,637 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArtworkService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtworkServiceTests
|
||||
{
|
||||
private readonly IEnvironmentContext _mockEnvironmentContext;
|
||||
private readonly IFileTypeService _mockFileTypeService;
|
||||
private readonly IFileProviderService _mockFileProviderService;
|
||||
private readonly IDirectoryProviderService _mockDirectoryProviderService;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly IHttpClientFactory _mockHttpClientFactory;
|
||||
private readonly IOptions<MediaSettingsDto> _mockMediaSettingsOptions;
|
||||
private readonly MusicArtworkService _sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly PathSegmentFixture _pathSegmentFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtworkServiceTests"/> class.
|
||||
/// </summary>
|
||||
public MusicArtworkServiceTests()
|
||||
{
|
||||
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
|
||||
_mockFileTypeService = Substitute.For<IFileTypeService>();
|
||||
_mockFileProviderService = Substitute.For<IFileProviderService>();
|
||||
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
|
||||
_mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
|
||||
_mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
|
||||
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
|
||||
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
|
||||
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
|
||||
|
||||
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books", musicDirectory: "music");
|
||||
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
|
||||
_mockMediaSettingsOptions.Value.Returns(mediaSettings);
|
||||
|
||||
_sut = new MusicArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
|
||||
MockPathBuilding();
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
MockPathBuilding();
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(), null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
|
||||
MockPathBuilding();
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("FileSystem.Error", result.FirstError.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteAlbumArtwork_WhenListingTheArtworkFilesFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
string albumTitle = "Test Album";
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files"));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("FileSystem.Error", result.FirstError.Code);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteAlbumArtwork_WhenCalled_ShouldDeleteEveryFileInTheAlbumDirectory()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
string albumTitle = "Test Album";
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
|
||||
FileSystemPathId bookletFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "booklet-1.jpg"));
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, bookletFileId]));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
|
||||
_mockFileProviderService.Received(1).DeleteFile(bookletFileId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteAlbumArtwork_WhenDeletingAFileFails_ShouldReturnTheErrorAndStopDeletingTheRemainingFiles()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
string albumTitle = "Test Album";
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
|
||||
FileSystemPathId bookletFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "booklet-1.jpg"));
|
||||
Error deleteError = Errors.FileSystemManagement.FileDeleteError;
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, bookletFileId]));
|
||||
_mockFileProviderService.DeleteFile(coverFileId).Returns(deleteError);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(deleteError, result.FirstError);
|
||||
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(bookletFileId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteAlbumArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any<FileSystemPathId>(), true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteAlbumArtwork_WhenBuildingTheDirectoryPathFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreItAsTheCoverAndDeleteTheTemporaryUpload()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
string albumTitle = "Test Album";
|
||||
byte[] uploadedBytes = [1, 2, 3, 4, 5, 6, 7, 8];
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
|
||||
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg");
|
||||
string? capturedTemporaryPath = null;
|
||||
byte[]? capturedBytes = null;
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
|
||||
capturedBytes = File.ReadAllBytes(capturedTemporaryPath);
|
||||
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.jpg")));
|
||||
});
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
|
||||
await using MemoryStream artworkStream = new(uploadedBytes);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
|
||||
Assert.NotNull(capturedTemporaryPath);
|
||||
Assert.StartsWith(Path.GetTempPath(), capturedTemporaryPath);
|
||||
Assert.EndsWith(".jpg", capturedTemporaryPath);
|
||||
Assert.Equal(uploadedBytes, capturedBytes);
|
||||
Assert.False(File.Exists(capturedTemporaryPath));
|
||||
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenAnArtworkStreamIsUploadedWithAReleaseType_ShouldStoreTheArtworkUnderTheReleaseTypeDirectory()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
string albumTitle = "Test Album";
|
||||
string releaseTypeName = "Single";
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle, releaseTypeName);
|
||||
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg");
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
|
||||
await using MemoryStream artworkStream = new([1, 2, 3]);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", releaseTypeName, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.Received(1).CopyFile(
|
||||
Arg.Any<FileSystemPathId>(),
|
||||
Arg.Is<FileSystemPathId>(pathId => pathId.Path == artworkDirectoryPath),
|
||||
true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenTheDownstreamStorageFails_ShouldStillDeleteTheTemporaryUpload()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
string albumTitle = "Test Album";
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
|
||||
string? capturedTemporaryPath = null;
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
|
||||
return Error.Failure("FileSystem.Error", "Failed to copy the artwork");
|
||||
});
|
||||
await using MemoryStream artworkStream = new([1, 2, 3, 4]);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("FileSystem.Error", result.FirstError.Code);
|
||||
Assert.NotNull(capturedTemporaryPath);
|
||||
Assert.False(File.Exists(capturedTemporaryPath));
|
||||
_mockFileProviderService.DidNotReceive().RenameFile(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("cover")] // A name without an extension falls back to the .img extension.
|
||||
[InlineData("")] // An empty name falls back to the .img extension.
|
||||
[InlineData(null)] // A null name falls back to the .img extension.
|
||||
public async Task SaveAlbumArtworkAsync_WhenTheUploadedFileNameHasNoExtension_ShouldBufferTheUploadWithTheImgExtension(string? fileName)
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
string albumTitle = "Test Album";
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
|
||||
string? capturedTemporaryPath = null;
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
|
||||
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.img")));
|
||||
});
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
await using MemoryStream artworkStream = new([1, 2, 3]);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, fileName!, null, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.NotNull(capturedTemporaryPath);
|
||||
Assert.EndsWith(".img", capturedTemporaryPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveArtistArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreItAsTheCoverAndDeleteTheTemporaryUpload()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
byte[] uploadedBytes = [9, 8, 7, 6, 5];
|
||||
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName);
|
||||
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.png");
|
||||
string? capturedTemporaryPath = null;
|
||||
byte[]? capturedBytes = null;
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.PNG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
|
||||
capturedBytes = File.ReadAllBytes(capturedTemporaryPath);
|
||||
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.png")));
|
||||
});
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.png")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
|
||||
await using MemoryStream artworkStream = new(uploadedBytes);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, artworkStream, "cover.png", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
|
||||
Assert.NotNull(capturedTemporaryPath);
|
||||
Assert.StartsWith(Path.GetTempPath(), capturedTemporaryPath);
|
||||
Assert.EndsWith(".png", capturedTemporaryPath);
|
||||
Assert.Equal(uploadedBytes, capturedBytes);
|
||||
Assert.False(File.Exists(capturedTemporaryPath));
|
||||
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.png");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveArtistArtworkAsync_WhenTheDownstreamStorageFails_ShouldStillDeleteTheTemporaryUpload()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string artistName = "Test Artist";
|
||||
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName);
|
||||
string? capturedTemporaryPath = null;
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.PNG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
|
||||
return Error.Failure("FileSystem.Error", "Failed to copy the artwork");
|
||||
});
|
||||
await using MemoryStream artworkStream = new([1, 2, 3]);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, artworkStream, "cover.png", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("FileSystem.Error", result.FirstError.Code);
|
||||
Assert.NotNull(capturedTemporaryPath);
|
||||
Assert.False(File.Exists(capturedTemporaryPath));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // A null path is a no-op.
|
||||
[InlineData("")] // An empty path is a no-op.
|
||||
[InlineData(" ")] // A whitespace path is a no-op.
|
||||
public void DeleteStoredArtwork_WhenThePathIsMissing_ShouldReturnDeletedWithoutTouchingTheFileSystem(string? artworkRelativePath)
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath!);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().FileExists(Arg.Any<FileSystemPathId>());
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteStoredArtwork_WhenTheFileDoesNotExist_ShouldReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
string artworkRelativePath = $"\\media\\music\\cover-{Guid.NewGuid():N}.jpg";
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteStoredArtwork_WhenTheFileExists_ShouldDeleteItAndReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
string artworkRelativePath = $"\\media\\music\\cover-{Guid.NewGuid():N}.jpg";
|
||||
string expectedAbsolutePath = Path.Combine(AppContext.BaseDirectory, artworkRelativePath.TrimStart('\\'));
|
||||
_mockFileProviderService.FileExists(Arg.Is<FileSystemPathId>(pathId => pathId.Path == expectedAbsolutePath))
|
||||
.Returns(Result.From(true));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.Received(1).DeleteFile(Arg.Is<FileSystemPathId>(pathId => pathId.Path == expectedAbsolutePath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteStoredArtwork_WhenTheExistenceCheckFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
string artworkRelativePath = "\\media\\music\\cover.jpg";
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("FileSystem.Error", result.FirstError.Code);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteStoredArtwork_WhenDeletingTheFileFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
string artworkRelativePath = "\\media\\music\\cover.jpg";
|
||||
Error error = Error.Failure("FileSystem.Error", "Failed to delete the artwork file");
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
_mockFileProviderService.Received(1).DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path service so that building the artwork directory paths succeeds.
|
||||
/// </summary>
|
||||
private void MockPathBuilding()
|
||||
{
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
string name = callInfo.Arg<string>();
|
||||
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
|
||||
});
|
||||
|
||||
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
string name = callInfo.ArgAt<string>(0);
|
||||
string identifier = callInfo.ArgAt<string>(1);
|
||||
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
|
||||
});
|
||||
|
||||
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path and file system services so that the artwork is stored into the given directory.
|
||||
/// </summary>
|
||||
/// <param name="artworkDirectoryPath">The file system path of the directory into which the artwork is stored.</param>
|
||||
private void MockArtworkDirectoryStubs(string artworkDirectoryPath)
|
||||
{
|
||||
MockPathBuilding();
|
||||
|
||||
// Every directory except the artwork directory itself already exists, so that only the final directory is created.
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>()))));
|
||||
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory that the artwork of the album is stored into.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist of the album.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="releaseTypeName">Optional. The name of the release type directory the album is stored under.</param>
|
||||
/// <returns>The expected file system path of the album artwork directory.</returns>
|
||||
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, string? releaseTypeName = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(releaseTypeName))
|
||||
{
|
||||
return Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"media",
|
||||
"music",
|
||||
$"{libraryName}-{libraryId}",
|
||||
$"{artistName}-{artistId}",
|
||||
$"{albumTitle}-{albumId}");
|
||||
}
|
||||
|
||||
return Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"media",
|
||||
"music",
|
||||
$"{libraryName}-{libraryId}",
|
||||
$"{artistName}-{artistId}",
|
||||
releaseTypeName,
|
||||
$"{albumTitle}-{albumId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory that the artwork of the artist is stored into.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <returns>The expected file system path of the artist artwork directory.</returns>
|
||||
private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, Guid artistId, string artistName)
|
||||
{
|
||||
return Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"media",
|
||||
"music",
|
||||
$"{libraryName}-{libraryId}",
|
||||
$"{artistName}-{artistId}");
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="AudioContainerResolver"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AudioContainerResolverTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(null, null)] // An absent mime type leaves the container unrecognized.
|
||||
[InlineData("", null)] // An empty mime type leaves the container unrecognized.
|
||||
[InlineData(" ", null)] // A blank mime type leaves the container unrecognized.
|
||||
[InlineData("taglib/wav", "WAV")] // The taglib prefix is dropped and the container is upper cased.
|
||||
[InlineData("taglib/png", "PNG")] // A container the resolver has no dedicated parser for still yields its name.
|
||||
[InlineData("audio/x-wavpack", "X-WAVPACK")] // The last segment of a standard mime type names the container.
|
||||
public void ResolveFromMimeType_WhenCalled_ShouldReturnTheContainerNamedByTheMimeType(string? mimeType, string? expectedContainer)
|
||||
{
|
||||
// Act
|
||||
string? container = AudioContainerResolver.ResolveFromMimeType(mimeType);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedContainer, container);
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
#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_WhenTheFirstAudioMetadataHasAContainer_ShouldKeepTheFirstContainer()
|
||||
{
|
||||
// Arrange
|
||||
AudioMetadataDto first = _audioMetadataDtoFixture.Create(container: "MP3");
|
||||
AudioMetadataDto second = _audioMetadataDtoFixture.Create(container: "FLAC");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MP3", merged.Container);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenTheFirstAudioMetadataHasNoContainer_ShouldTakeTheSecondContainer()
|
||||
{
|
||||
// Arrange
|
||||
AudioMetadataDto first = _audioMetadataDtoFixture.Create(includeContainer: false);
|
||||
AudioMetadataDto second = _audioMetadataDtoFixture.Create(container: "FLAC");
|
||||
|
||||
// Act
|
||||
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("FLAC", merged.Container);
|
||||
}
|
||||
|
||||
[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);
|
||||
}
|
||||
}
|
||||
+444
@@ -0,0 +1,444 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PlaybackDeliveryHandleService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaybackDeliveryHandleServiceTests
|
||||
{
|
||||
private readonly PlaybackDeliveryHandleService _sut;
|
||||
private readonly PlaybackDeliveryHandleDtoFixture _playbackDeliveryHandleDtoFixture = new();
|
||||
private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaybackDeliveryHandleServiceTests"/> class.
|
||||
/// </summary>
|
||||
public PlaybackDeliveryHandleServiceTests()
|
||||
{
|
||||
_sut = new PlaybackDeliveryHandleService();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueDeliveryId_WhenCalled_ShouldReturnA32CharacterLowercaseHexadecimalHandle()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
|
||||
|
||||
// Act
|
||||
string handle = _sut.IssueDeliveryId(delivery);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(32, handle.Length);
|
||||
Assert.Matches("^[0-9a-f]{32}$", handle);
|
||||
Assert.True(PlaybackDeliveryId.IsValid(handle));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueDeliveryId_WhenDeliveriesDiffer_ShouldReturnDistinctHandles()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleDto firstDelivery = CreateBaseDelivery();
|
||||
PlaybackDeliveryHandleDto secondDelivery = CreateBaseDelivery();
|
||||
|
||||
// Act
|
||||
string firstHandle = _sut.IssueDeliveryId(firstDelivery);
|
||||
string secondHandle = _sut.IssueDeliveryId(secondDelivery);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(firstHandle, secondHandle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueDeliveryId_WhenTheSameDeliveryIsIssuedAgain_ShouldReturnTheSameHandle()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
|
||||
|
||||
// Act
|
||||
string firstHandle = _sut.IssueDeliveryId(delivery);
|
||||
string secondHandle = _sut.IssueDeliveryId(delivery);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstHandle, secondHandle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueDeliveryId_WhenAnEqualDeliveryIsIssuedAgainAtThePerUserLimit_ShouldReuseTheExistingHandle()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
|
||||
string handle = _sut.IssueDeliveryId(delivery);
|
||||
// Fill the rest of the per user bound with distinct deliveries, so the next issue would evict this one if it did not reuse it.
|
||||
for (int index = 0; index < 63; index++)
|
||||
_sut.IssueDeliveryId(CreateDeliveryFor(delivery.Request.UserId));
|
||||
PlaybackDeliveryHandleDto equalDelivery = delivery with { Request = delivery.Request with { AllowedRoots = [.. delivery.Request.AllowedRoots] } };
|
||||
|
||||
// Act
|
||||
string reusedHandle = _sut.IssueDeliveryId(equalDelivery);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(handle, reusedHandle);
|
||||
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, delivery.Request.UserId, delivery.Request.TrackId);
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(delivery, result.Value);
|
||||
}
|
||||
|
||||
public static TheoryData<DeliveryVariation> SignatureVariations => new()
|
||||
{
|
||||
DeliveryVariation.UserId,
|
||||
DeliveryVariation.TrackId,
|
||||
DeliveryVariation.LibraryId,
|
||||
DeliveryVariation.AlbumId,
|
||||
DeliveryVariation.ArtistId,
|
||||
DeliveryVariation.Mode,
|
||||
DeliveryVariation.Shape,
|
||||
DeliveryVariation.SourceContainer,
|
||||
DeliveryVariation.SourceContainerNull,
|
||||
DeliveryVariation.Container,
|
||||
DeliveryVariation.Codec,
|
||||
DeliveryVariation.SegmentDurationSeconds,
|
||||
DeliveryVariation.DurationInSeconds,
|
||||
DeliveryVariation.Bitrate,
|
||||
DeliveryVariation.BitrateNull,
|
||||
DeliveryVariation.SampleRate,
|
||||
DeliveryVariation.Channels,
|
||||
DeliveryVariation.BitDepth,
|
||||
DeliveryVariation.BitDepthNull,
|
||||
DeliveryVariation.Quality,
|
||||
DeliveryVariation.SourcePath,
|
||||
DeliveryVariation.SourceLength,
|
||||
DeliveryVariation.SourceLastModifiedUtc,
|
||||
DeliveryVariation.AllowedRoots
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(SignatureVariations))]
|
||||
public void IssueDeliveryId_WhenOneSignatureInputChanges_ShouldReturnADifferentHandle(DeliveryVariation variation)
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
|
||||
string handle = _sut.IssueDeliveryId(delivery);
|
||||
PlaybackDeliveryHandleDto variedDelivery = Vary(delivery, variation);
|
||||
|
||||
// Act
|
||||
string variedHandle = _sut.IssueDeliveryId(variedDelivery);
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(handle, variedHandle);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // An absent handle cannot address a delivery.
|
||||
[InlineData("")] // An empty handle cannot address a delivery.
|
||||
[InlineData(" ")] // A whitespace handle cannot address a delivery.
|
||||
[InlineData("0123456789abcdef0123456789abcdef")] // A well formed handle that was never issued.
|
||||
public void GetDelivery_WhenTheHandleIsMissingOrUnknown_ShouldReturnPlaybackDeliveryNotFoundError(string? deliveryId)
|
||||
{
|
||||
// Act
|
||||
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(deliveryId, Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDelivery_WhenTheHandleWasIssuedToAnotherUser_ShouldReturnPlaybackDeliveryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
|
||||
string handle = _sut.IssueDeliveryId(delivery);
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, Guid.NewGuid(), delivery.Request.TrackId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDelivery_WhenTheHandleDescribesAnotherTrack_ShouldReturnPlaybackDeliveryNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
|
||||
string handle = _sut.IssueDeliveryId(delivery);
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, delivery.Request.UserId, Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDelivery_WhenTheHandleWasIssuedToTheUserForTheTrack_ShouldReturnTheIssuedDelivery()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
|
||||
string handle = _sut.IssueDeliveryId(delivery);
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, delivery.Request.UserId, delivery.Request.TrackId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Same(delivery, result.Value);
|
||||
Assert.Equal(delivery.Request.TrackId, result.Value.Request.TrackId);
|
||||
Assert.Equal(delivery.Request.UserId, result.Value.Request.UserId);
|
||||
Assert.Equal(delivery.Shape, result.Value.Shape);
|
||||
Assert.Equal(delivery.LibraryId, result.Value.LibraryId);
|
||||
Assert.Equal(delivery.AlbumId, result.Value.AlbumId);
|
||||
Assert.Equal(delivery.ArtistId, result.Value.ArtistId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueDeliveryId_WhenAUserExceedsThePerUserLimit_ShouldEvictOnlyTheOldestHandleOfThatUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
PlaybackDeliveryHandleDto otherUserDelivery = CreateDeliveryFor(otherUserId);
|
||||
string otherUserHandle = _sut.IssueDeliveryId(otherUserDelivery);
|
||||
List<(string Handle, Guid TrackId)> handles = [];
|
||||
for (int index = 0; index < 64; index++)
|
||||
{
|
||||
PlaybackDeliveryHandleDto delivery = CreateDeliveryFor(userId);
|
||||
handles.Add((_sut.IssueDeliveryId(delivery), delivery.Request.TrackId));
|
||||
}
|
||||
|
||||
// Act
|
||||
PlaybackDeliveryHandleDto newestDelivery = CreateDeliveryFor(userId);
|
||||
string newestHandle = _sut.IssueDeliveryId(newestDelivery);
|
||||
|
||||
// Assert
|
||||
Assert.True(_sut.GetDelivery(handles[0].Handle, userId, handles[0].TrackId).IsFailure);
|
||||
for (int index = 1; index < handles.Count; index++)
|
||||
Assert.True(_sut.GetDelivery(handles[index].Handle, userId, handles[index].TrackId).IsSuccess);
|
||||
Assert.True(_sut.GetDelivery(newestHandle, userId, newestDelivery.Request.TrackId).IsSuccess);
|
||||
Assert.True(_sut.GetDelivery(otherUserHandle, otherUserId, otherUserDelivery.Request.TrackId).IsSuccess);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueDeliveryId_WhenTheGlobalLimitIsExceeded_ShouldEvictOnlyTheOldestHandle()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleService sut = new();
|
||||
Guid[] users = [.. Enumerable.Range(0, 400).Select(_ => Guid.NewGuid())];
|
||||
string? oldestHandle = null;
|
||||
Guid oldestUserId = Guid.Empty;
|
||||
Guid oldestTrackId = Guid.Empty;
|
||||
string? secondOldestHandle = null;
|
||||
Guid secondOldestUserId = Guid.Empty;
|
||||
Guid secondOldestTrackId = Guid.Empty;
|
||||
string? newestHandle = null;
|
||||
Guid newestUserId = Guid.Empty;
|
||||
Guid newestTrackId = Guid.Empty;
|
||||
for (int index = 0; index < 20_000; index++)
|
||||
{
|
||||
// The per user bound is 64, so each user is given exactly 64 deliveries and never triggers a per user eviction.
|
||||
Guid userId = users[index / 64];
|
||||
PlaybackDeliveryHandleDto delivery = CreateDeliveryFor(userId);
|
||||
string handle = sut.IssueDeliveryId(delivery);
|
||||
if (index == 0)
|
||||
{
|
||||
oldestHandle = handle;
|
||||
oldestUserId = userId;
|
||||
oldestTrackId = delivery.Request.TrackId;
|
||||
}
|
||||
else if (index == 1)
|
||||
{
|
||||
secondOldestHandle = handle;
|
||||
secondOldestUserId = userId;
|
||||
secondOldestTrackId = delivery.Request.TrackId;
|
||||
}
|
||||
if (index == 19_999)
|
||||
{
|
||||
newestHandle = handle;
|
||||
newestUserId = userId;
|
||||
newestTrackId = delivery.Request.TrackId;
|
||||
}
|
||||
}
|
||||
PlaybackDeliveryHandleDto extraDelivery = CreateDeliveryFor(Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
string extraHandle = sut.IssueDeliveryId(extraDelivery);
|
||||
|
||||
// Assert
|
||||
Assert.True(sut.GetDelivery(oldestHandle, oldestUserId, oldestTrackId).IsFailure);
|
||||
Assert.True(sut.GetDelivery(secondOldestHandle, secondOldestUserId, secondOldestTrackId).IsSuccess);
|
||||
Assert.True(sut.GetDelivery(newestHandle, newestUserId, newestTrackId).IsSuccess);
|
||||
Assert.True(sut.GetDelivery(extraHandle, extraDelivery.Request.UserId, extraDelivery.Request.TrackId).IsSuccess);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IssueDeliveryId_WhenTheSameDeliveryIsIssuedConcurrently_ShouldReturnOneIdenticalHandle()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
|
||||
|
||||
// Act
|
||||
string[] handles = await Task.WhenAll(Enumerable.Range(0, 32).Select(_ => Task.Run(() => _sut.IssueDeliveryId(delivery))));
|
||||
|
||||
// Assert
|
||||
Assert.Single(handles.Distinct());
|
||||
Assert.True(_sut.GetDelivery(handles[0], delivery.Request.UserId, delivery.Request.TrackId).IsSuccess);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IssueDeliveryId_WhenDifferentDeliveriesAreIssuedConcurrently_ShouldMakeEveryHandleResolvable()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackDeliveryHandleDto[] deliveries = [.. Enumerable.Range(0, 32).Select(_ => CreateDeliveryFor(Guid.NewGuid()))];
|
||||
|
||||
// Act
|
||||
string[] handles = await Task.WhenAll(deliveries.Select(delivery => Task.Run(() => _sut.IssueDeliveryId(delivery))));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(deliveries.Length, handles.Distinct().Count());
|
||||
for (int index = 0; index < deliveries.Length; index++)
|
||||
Assert.True(_sut.GetDelivery(handles[index], deliveries[index].Request.UserId, deliveries[index].Request.TrackId).IsSuccess);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The single input of the delivery signature that a variation changes.
|
||||
/// </summary>
|
||||
public enum DeliveryVariation
|
||||
{
|
||||
UserId,
|
||||
TrackId,
|
||||
LibraryId,
|
||||
AlbumId,
|
||||
ArtistId,
|
||||
Mode,
|
||||
Shape,
|
||||
SourceContainer,
|
||||
SourceContainerNull,
|
||||
Container,
|
||||
Codec,
|
||||
SegmentDurationSeconds,
|
||||
DurationInSeconds,
|
||||
Bitrate,
|
||||
BitrateNull,
|
||||
SampleRate,
|
||||
Channels,
|
||||
BitDepth,
|
||||
BitDepthNull,
|
||||
Quality,
|
||||
SourcePath,
|
||||
SourceLength,
|
||||
SourceLastModifiedUtc,
|
||||
AllowedRoots
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a delivery with every signature input explicitly pinned.
|
||||
/// </summary>
|
||||
/// <returns>The created delivery.</returns>
|
||||
private PlaybackDeliveryHandleDto CreateBaseDelivery()
|
||||
{
|
||||
return _playbackDeliveryHandleDtoFixture.Create(
|
||||
request: CreateRequest(userId: Guid.NewGuid(), trackId: Guid.NewGuid()),
|
||||
shape: PlaybackDeliveryShape.TimeAddressedSegments,
|
||||
libraryId: Guid.Parse("11111111-1111-1111-1111-111111111111"),
|
||||
albumId: Guid.Parse("22222222-2222-2222-2222-222222222222"),
|
||||
artistId: Guid.Parse("33333333-3333-3333-3333-333333333333"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a delivery for a user whose track is unique to the delivery.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user the delivery is issued to.</param>
|
||||
/// <returns>The created delivery.</returns>
|
||||
private PlaybackDeliveryHandleDto CreateDeliveryFor(Guid userId)
|
||||
{
|
||||
return _playbackDeliveryHandleDtoFixture.Create(
|
||||
request: CreateRequest(userId: userId, trackId: Guid.NewGuid()),
|
||||
shape: PlaybackDeliveryShape.TimeAddressedSegments,
|
||||
libraryId: Guid.NewGuid(),
|
||||
albumId: Guid.NewGuid(),
|
||||
artistId: Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes exactly one input of the delivery signature.
|
||||
/// </summary>
|
||||
/// <param name="delivery">The delivery to vary.</param>
|
||||
/// <param name="variation">The input to change.</param>
|
||||
/// <returns>The varied delivery.</returns>
|
||||
private static PlaybackDeliveryHandleDto Vary(PlaybackDeliveryHandleDto delivery, DeliveryVariation variation)
|
||||
{
|
||||
return variation switch
|
||||
{
|
||||
DeliveryVariation.UserId => delivery with { Request = delivery.Request with { UserId = Guid.NewGuid() } },
|
||||
DeliveryVariation.TrackId => delivery with { Request = delivery.Request with { TrackId = Guid.NewGuid() } },
|
||||
DeliveryVariation.LibraryId => delivery with { LibraryId = Guid.NewGuid() },
|
||||
DeliveryVariation.AlbumId => delivery with { AlbumId = Guid.NewGuid() },
|
||||
DeliveryVariation.ArtistId => delivery with { ArtistId = Guid.NewGuid() },
|
||||
DeliveryVariation.Mode => delivery with { Request = delivery.Request with { Mode = PlaybackDeliveryMode.Remux } },
|
||||
DeliveryVariation.Shape => delivery with { Shape = PlaybackDeliveryShape.ByteRangeSeekable },
|
||||
DeliveryVariation.SourceContainer => delivery with { Request = delivery.Request with { SourceContainer = "WAV" } },
|
||||
DeliveryVariation.SourceContainerNull => delivery with { Request = delivery.Request with { SourceContainer = null } },
|
||||
DeliveryVariation.Container => delivery with { Request = delivery.Request with { Container = "AAC" } },
|
||||
DeliveryVariation.Codec => delivery with { Request = delivery.Request with { Codec = "AAC" } },
|
||||
DeliveryVariation.SegmentDurationSeconds => delivery with { Request = delivery.Request with { SegmentDurationSeconds = 10 } },
|
||||
DeliveryVariation.DurationInSeconds => delivery with { Request = delivery.Request with { DurationInSeconds = 300 } },
|
||||
DeliveryVariation.Bitrate => delivery with { Request = delivery.Request with { Bitrate = 320 } },
|
||||
DeliveryVariation.BitrateNull => delivery with { Request = delivery.Request with { Bitrate = null } },
|
||||
DeliveryVariation.SampleRate => delivery with { Request = delivery.Request with { SampleRate = 96000 } },
|
||||
DeliveryVariation.Channels => delivery with { Request = delivery.Request with { Channels = 6 } },
|
||||
DeliveryVariation.BitDepth => delivery with { Request = delivery.Request with { BitDepth = 16 } },
|
||||
DeliveryVariation.BitDepthNull => delivery with { Request = delivery.Request with { BitDepth = null } },
|
||||
DeliveryVariation.Quality => delivery with { Request = delivery.Request with { Quality = PlaybackStreamingQuality.Low } },
|
||||
DeliveryVariation.SourcePath => delivery with { Request = delivery.Request with { SourcePath = "/music/incoming/other.flac" } },
|
||||
DeliveryVariation.SourceLength => delivery with { Request = delivery.Request with { SourceLength = 999 } },
|
||||
DeliveryVariation.SourceLastModifiedUtc => delivery with { Request = delivery.Request with { SourceLastModifiedUtc = new DateTime(2026, 2, 3, 4, 5, 6, DateTimeKind.Utc) } },
|
||||
DeliveryVariation.AllowedRoots => delivery with { Request = delivery.Request with { AllowedRoots = [.. delivery.Request.AllowedRoots.Take(1), "/music/other"] } },
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(variation), variation, "Unsupported delivery variation.")
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a normalization request with every signature input explicitly pinned.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user the delivery is issued to.</param>
|
||||
/// <param name="trackId">The Id of the track the delivery describes.</param>
|
||||
/// <returns>The created request.</returns>
|
||||
private NormalizedTrackRequestDto CreateRequest(Guid userId, Guid trackId)
|
||||
{
|
||||
return _normalizedTrackRequestDtoFixture.Create(
|
||||
trackId: trackId,
|
||||
userId: userId,
|
||||
sourcePath: "/music/library/track.flac",
|
||||
allowedRoots: ["/music/library", "/music/incoming"],
|
||||
sourceContainer: "FLAC",
|
||||
mode: PlaybackDeliveryMode.Transcode,
|
||||
container: "MP3",
|
||||
codec: "MP3",
|
||||
segmentDurationSeconds: 6,
|
||||
durationInSeconds: 245,
|
||||
bitrate: 900,
|
||||
sampleRate: 48000,
|
||||
channels: 2,
|
||||
bitDepth: 24,
|
||||
quality: PlaybackStreamingQuality.High,
|
||||
sourceLength: 123456,
|
||||
sourceLastModifiedUtc: new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc));
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PlaybackFormatCatalog"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaybackFormatCatalogTests
|
||||
{
|
||||
[Fact]
|
||||
public void Formats_WhenRead_ShouldExposeTheDocumentedCanonicalContainerAndCodecPairsInPreferenceOrder()
|
||||
{
|
||||
// Arrange
|
||||
(string Container, string Codec)[] expectedPairs =
|
||||
[
|
||||
("MP4", "AAC"), // The preferred container of the preferred codec.
|
||||
("AAC", "AAC"), // The second container of the preferred codec.
|
||||
("OGG", "OPUS"), // The preferred lossy codec after AAC.
|
||||
("MP3", "MP3"), // The compatibility codec.
|
||||
("OGG", "VORBIS"), // The second lossy codec in OGG.
|
||||
("FLAC", "FLAC"), // The lossless codec.
|
||||
("WAV", "PCM") // The uncompressed codec.
|
||||
];
|
||||
|
||||
// Act
|
||||
IReadOnlyList<NormalizedAudioFormatDto> result = PlaybackFormatCatalog.Formats;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedPairs, result.Select(format => (format.Container, format.Codec)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TranscodeCodecPreference_WhenRead_ShouldListEachCodecOnceInOrderOfFirstAppearanceInFormats()
|
||||
{
|
||||
// Arrange
|
||||
List<string> expectedCodecs = [];
|
||||
foreach (NormalizedAudioFormatDto format in PlaybackFormatCatalog.Formats)
|
||||
if (!expectedCodecs.Contains(format.Codec, StringComparer.OrdinalIgnoreCase))
|
||||
expectedCodecs.Add(format.Codec);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<string> result = PlaybackFormatCatalog.TranscodeCodecPreference;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedCodecs, result);
|
||||
Assert.Equal(["AAC", "OPUS", "MP3", "VORBIS", "FLAC", "PCM"], result);
|
||||
Assert.Equal(result.Count, result.Distinct(StringComparer.OrdinalIgnoreCase).Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProducibleContainersByCodec_WhenRead_ShouldGroupTheContainersPerCodecInCatalogOrder()
|
||||
{
|
||||
// Arrange
|
||||
Dictionary<string, List<string>> expectedContainersByCodec = new(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (NormalizedAudioFormatDto format in PlaybackFormatCatalog.Formats)
|
||||
{
|
||||
if (!expectedContainersByCodec.TryGetValue(format.Codec, out List<string>? containers))
|
||||
{
|
||||
containers = [];
|
||||
expectedContainersByCodec[format.Codec] = containers;
|
||||
}
|
||||
containers.Add(format.Container);
|
||||
}
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlyList<string>> result = PlaybackFormatCatalog.ProducibleContainersByCodec;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedContainersByCodec.Count, result.Count);
|
||||
foreach (KeyValuePair<string, List<string>> expectedEntry in expectedContainersByCodec)
|
||||
{
|
||||
Assert.True(result.TryGetValue(expectedEntry.Key, out IReadOnlyList<string>? containers));
|
||||
Assert.Equal(expectedEntry.Value, containers);
|
||||
}
|
||||
Assert.Equal(["MP4", "AAC"], result["AAC"]); // The preferred codec has two producible containers, in preference order.
|
||||
Assert.Equal(["OGG"], result["OPUS"]);
|
||||
Assert.Equal(["OGG"], result["VORBIS"]);
|
||||
Assert.Equal(["MP3"], result["MP3"]);
|
||||
Assert.Equal(["FLAC"], result["FLAC"]);
|
||||
Assert.Equal(["WAV"], result["PCM"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProducibleContainersByCodec_WhenRead_ShouldNotRepeatAContainerWithinACodec()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlyList<string>> result = PlaybackFormatCatalog.ProducibleContainersByCodec;
|
||||
|
||||
// Assert
|
||||
foreach (IReadOnlyList<string> containers in result.Values)
|
||||
Assert.Equal(containers.Count, containers.Distinct(StringComparer.OrdinalIgnoreCase).Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProducibleContainersByCodec_WhenRead_ShouldOnlyContainPairsThatExistInTheCatalog()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlyList<string>> result = PlaybackFormatCatalog.ProducibleContainersByCodec;
|
||||
|
||||
// Assert
|
||||
foreach (KeyValuePair<string, IReadOnlyList<string>> entry in result)
|
||||
foreach (string container in entry.Value)
|
||||
Assert.Contains(PlaybackFormatCatalog.Formats, format =>
|
||||
string.Equals(format.Codec, entry.Key, StringComparison.OrdinalIgnoreCase) &&
|
||||
string.Equals(format.Container, container, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FormatsByPair_WhenRead_ShouldContainExactlyOneEntryPerCatalogFormat()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyDictionary<string, NormalizedAudioFormatDto> result = PlaybackFormatCatalog.FormatsByPair;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(PlaybackFormatCatalog.Formats.Count, result.Count);
|
||||
Assert.All(PlaybackFormatCatalog.Formats, format =>
|
||||
{
|
||||
string pairKey = PlaybackFormatCatalog.BuildPairKey(format.Container, format.Codec);
|
||||
Assert.True(result.TryGetValue(pairKey, out NormalizedAudioFormatDto? indexedFormat));
|
||||
Assert.Equal(format, indexedFormat);
|
||||
});
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("mp4/aac", "MP4", "AAC")] // The canonical pair in lower case.
|
||||
[InlineData("Mp4/Aac", "MP4", "AAC")] // The canonical pair in mixed case.
|
||||
[InlineData("aac/aac", "AAC", "AAC")] // The second format in the catalog, in lower case.
|
||||
public void FormatsByPair_WhenLookedUpWithDifferentCasing_ShouldReturnTheCatalogFormat(string pairKey, string expectedContainer, string expectedCodec)
|
||||
{
|
||||
// Act
|
||||
bool found = PlaybackFormatCatalog.FormatsByPair.TryGetValue(pairKey, out NormalizedAudioFormatDto? result);
|
||||
|
||||
// Assert
|
||||
Assert.True(found);
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(expectedContainer, result.Container);
|
||||
Assert.Equal(expectedCodec, result.Codec);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildPairKey_WhenTheInputsArePaddedAndDifferentlyCased_ShouldTrimAndUppercaseThem()
|
||||
{
|
||||
// Act
|
||||
string result = PlaybackFormatCatalog.BuildPairKey(" mp4 ", "\taAc ");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("MP4/AAC", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildPairKey_WhenTheInputsDifferOnlyInCasingAndPadding_ShouldProduceTheSameKey()
|
||||
{
|
||||
// Act
|
||||
string firstResult = PlaybackFormatCatalog.BuildPairKey("mp4", "aac");
|
||||
string secondResult = PlaybackFormatCatalog.BuildPairKey(" MP4 ", " AAC ");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(firstResult, secondResult);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null, "/")] // Both parts are absent.
|
||||
[InlineData("", "", "/")] // Both parts are empty.
|
||||
[InlineData(" ", " ", "/")] // Both parts are white space.
|
||||
[InlineData(null, "aac", "/AAC")] // Only the container is absent.
|
||||
[InlineData("mp4", null, "MP4/")] // Only the codec is absent.
|
||||
public void BuildPairKey_WhenAContainerOrCodecIsNullOrEmpty_ShouldProduceTheSlashSeparatedFormWithoutThrowing(string? container, string? codec, string expectedKey)
|
||||
{
|
||||
// Act
|
||||
string result = PlaybackFormatCatalog.BuildPairKey(container!, codec!);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedKey, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Formats_WhenRead_ShouldExposeANonEmptyMuxerALeadingDotExtensionAndANonEmptyEncoderForEveryFormat()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<NormalizedAudioFormatDto> result = PlaybackFormatCatalog.Formats;
|
||||
|
||||
// Assert
|
||||
Assert.All(result, format =>
|
||||
{
|
||||
Assert.False(string.IsNullOrWhiteSpace(format.MuxerName));
|
||||
Assert.StartsWith(".", format.FileExtension, StringComparison.Ordinal);
|
||||
Assert.True(format.FileExtension.Length > 1);
|
||||
Assert.False(string.IsNullOrWhiteSpace(format.EncoderName));
|
||||
});
|
||||
}
|
||||
}
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PlaybackFormatService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaybackFormatServiceTests
|
||||
{
|
||||
private readonly PlaybackFormatService _sut;
|
||||
private readonly PlaybackSourceFormatDtoFixture _playbackSourceFormatDtoFixture = new();
|
||||
private readonly PlaybackCapabilityDtoFixture _playbackCapabilityDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaybackFormatServiceTests"/> class.
|
||||
/// </summary>
|
||||
public PlaybackFormatServiceTests()
|
||||
{
|
||||
_sut = new PlaybackFormatService();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecideDelivery_WhenPlayerAdvertisesTheStoredFormat_ShouldReturnDirectPlay()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "FLAC", codec: "FLAC");
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC")];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode);
|
||||
Assert.Equal("FLAC", result.Value.Container);
|
||||
Assert.Equal("FLAC", result.Value.Codec);
|
||||
Assert.Equal(PlaybackDeliveryShape.ByteRangeSeekable, result.Value.Shape);
|
||||
Assert.Equal(0, result.Value.SegmentDurationSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecideDelivery_WhenPlayerDecodesTheCodecButNotTheContainer_ShouldReturnRemux()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM");
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities =
|
||||
[
|
||||
_playbackCapabilityDtoFixture.Create(container: "WAV", codec: "PCM"),
|
||||
_playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC")
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
|
||||
Assert.Equal("WAV", result.Value.Container);
|
||||
Assert.Equal("PCM", result.Value.Codec);
|
||||
Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, result.Value.Shape);
|
||||
Assert.Equal(6, result.Value.SegmentDurationSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecideDelivery_WhenPlayerCannotDecodeTheStoredCodec_ShouldReturnTranscode()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "WMA", codec: "WMA");
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
|
||||
Assert.Equal("MP3", result.Value.Container);
|
||||
Assert.Equal("MP3", result.Value.Codec);
|
||||
Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, result.Value.Shape);
|
||||
Assert.Equal(6, result.Value.SegmentDurationSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecideDelivery_WhenTheDefaultCapabilitiesAreUsed_ShouldReturnDirectPlay()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP3", codec: "MP3");
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, PlaybackCapabilitiesParser.Default);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecideDelivery_WhenDefaultCapabilitiesAreUsedForAnAacTrackInMp4_ShouldReturnRemuxToRawAac()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP4", codec: "AAC");
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, PlaybackCapabilitiesParser.Default);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
|
||||
Assert.Equal("AAC", result.Value.Container);
|
||||
Assert.Equal("AAC", result.Value.Codec);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("MP3", "MPEG-1 Layer 3", "MP3")] // The free form description of an MPEG-1 Layer 3 stream.
|
||||
[InlineData("MP3", "MP3", "MP3")] // A codec that is already named canonically.
|
||||
[InlineData("FLAC", "Flac", "FLAC")] // The description of a FLAC stream.
|
||||
[InlineData("OGG", "Vorbis I", "VORBIS")] // The description of a Vorbis stream.
|
||||
[InlineData("OGG", "Opus", "OPUS")] // The description of an Opus stream.
|
||||
[InlineData("MP4", "Apple Lossless", "ALAC")] // The description of an Apple Lossless stream.
|
||||
[InlineData("AAC", "MPEG-4 AAC", "AAC")] // A description naming both MPEG and AAC is AAC, not MP3.
|
||||
[InlineData("WAV", "PCM", "PCM")] // The description of an uncompressed stream.
|
||||
[InlineData("WAV", "Uncompressed", "PCM")] // Another description of an uncompressed stream.
|
||||
[InlineData("WMA", "Windows Media Audio", "WMA")] // The description of a Windows Media stream.
|
||||
public void DecideDelivery_WhenTheStoredCodecDescriptionIsRecognizable_ShouldCanonicalizeItAndDirectPlay(string container, string codecDescription, string canonicalCodec)
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: container, codec: codecDescription);
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: container, codec: canonicalCodec)];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode);
|
||||
Assert.Equal(canonicalCodec, result.Value.Codec);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("MPEG-1 Layer 2")] // MP2 shares the MP3 container but an MP3 decoder cannot decode it.
|
||||
[InlineData("MPEG-1 Layer 1")] // MP1 shares the MP3 container but an MP3 decoder cannot decode it.
|
||||
[InlineData("MPEG-4 Audio")] // A description that names no decodable codec is not mistaken for MP3.
|
||||
public void DecideDelivery_WhenAnMpegDescriptionIsNotLayer3_ShouldReturnTranscode(string codecDescription)
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP3", codec: codecDescription);
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null)] // An absent probe result names no codec.
|
||||
[InlineData("", "")] // An empty probe result names no codec.
|
||||
[InlineData("MP3", "AC-3")] // A codec description the server does not recognize.
|
||||
public void DecideDelivery_WhenTheStoredFormatIsUnknown_ShouldReturnTranscode(string? container, string? codec)
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(
|
||||
container: container,
|
||||
codec: codec,
|
||||
includeContainer: container is not null,
|
||||
includeCodec: codec is not null);
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecideDelivery_WhenSeveralProducibleCodecsAreAdvertised_ShouldTranscodeToTheMostPreferredOne()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "OGG", codec: "OPUS");
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities =
|
||||
[
|
||||
_playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC"),
|
||||
_playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC")
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
|
||||
Assert.Equal("AAC", result.Value.Codec);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecideDelivery_WhenSeveralContainersAreAdvertisedForTheSameCodec_ShouldRemuxToThePreferredContainer()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MATROSKA", codec: "AAC");
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities =
|
||||
[
|
||||
_playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC"),
|
||||
_playbackCapabilityDtoFixture.Create(container: "MP4", codec: "AAC")
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
|
||||
Assert.Equal("MP4", result.Value.Container);
|
||||
Assert.Equal("AAC", result.Value.Codec);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecideDelivery_WhenThePreferredContainerForTheCodecIsNotAdvertised_ShouldRemuxToTheOtherProducibleContainer()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MATROSKA", codec: "AAC");
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC")];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
|
||||
Assert.Equal("AAC", result.Value.Container);
|
||||
Assert.Equal("AAC", result.Value.Codec);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecideDelivery_WhenThePlayerNamesAContainerTheServerDoesNotProduce_ShouldDeliverTheServerContainer()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM");
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities =
|
||||
[
|
||||
_playbackCapabilityDtoFixture.Create(container: "evil;$(x)", codec: "PCM"),
|
||||
_playbackCapabilityDtoFixture.Create(container: "wav", codec: "pcm")
|
||||
];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
|
||||
Assert.Equal("WAV", result.Value.Container);
|
||||
Assert.Equal("PCM", result.Value.Codec);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecideDelivery_WhenThePlayerOnlyNamesContainersTheServerDoesNotProduce_ShouldReturnNoSupportedPlaybackFormat()
|
||||
{
|
||||
// Arrange
|
||||
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM");
|
||||
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "evil;$(x)", codec: "PCM")];
|
||||
|
||||
// Act
|
||||
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Playback.NoSupportedPlaybackFormat, result.FirstError);
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.IO.Abstractions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TrackNormalizationService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TrackNormalizationServiceTests : IDisposable
|
||||
{
|
||||
private readonly TrackNormalizationService _sut;
|
||||
private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new();
|
||||
private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new();
|
||||
private readonly string _sandboxRoot;
|
||||
private readonly string _cacheDirectory;
|
||||
private readonly string _sourceRoot;
|
||||
private readonly string _sourcePath;
|
||||
private readonly long _sourceLength;
|
||||
private readonly DateTime _sourceLastModifiedUtc;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TrackNormalizationServiceTests"/> class.
|
||||
/// </summary>
|
||||
public TrackNormalizationServiceTests()
|
||||
{
|
||||
_sandboxRoot = Path.Combine(Path.GetTempPath(), "lumina-track-normalization-tests-" + Guid.NewGuid().ToString("N"));
|
||||
_cacheDirectory = Path.Combine(_sandboxRoot, "cache");
|
||||
_sourceRoot = Path.Combine(_sandboxRoot, "source");
|
||||
_sourcePath = Path.Combine(_sourceRoot, "track.flac");
|
||||
Directory.CreateDirectory(_cacheDirectory);
|
||||
Directory.CreateDirectory(_sourceRoot);
|
||||
File.WriteAllBytes(_sourcePath, new byte[512]);
|
||||
_sourceLength = new FileInfo(_sourcePath).Length;
|
||||
_sourceLastModifiedUtc = File.GetLastWriteTimeUtc(_sourcePath);
|
||||
|
||||
// The real path service is used, with the real path strategy of the current platform, so containment follows the file system rules of the host.
|
||||
IPlatformContext platformContext = Substitute.For<IPlatformContext>();
|
||||
IPathStrategy pathStrategy = OperatingSystem.IsWindows()
|
||||
? new WindowsPathStrategy(new FileSystem())
|
||||
: new UnixPathStrategy(new FileSystem());
|
||||
platformContext.PathStrategy.Returns(pathStrategy);
|
||||
IPlatformContextManager platformContextManager = Substitute.For<IPlatformContextManager>();
|
||||
platformContextManager.GetCurrentContext().Returns(platformContext);
|
||||
IPathService pathService = new PathService(platformContextManager);
|
||||
|
||||
TranscodingSettingsDto settings = _transcodingSettingsDtoFixture.Create(
|
||||
ffmpegPath: Path.Combine(_sandboxRoot, "missing-ffmpeg"),
|
||||
maxConcurrentJobs: 2,
|
||||
maxConcurrentJobsPerUser: 1,
|
||||
maxCacheBytes: 100 * 1024 * 1024,
|
||||
jobTimeoutSeconds: 60,
|
||||
evictionGraceSeconds: 10,
|
||||
cacheDirectory: _cacheDirectory);
|
||||
TranscodingToolchainStatus toolchainStatus = new();
|
||||
_sut = new TrackNormalizationService(Options.Create(settings), NullLogger<TrackNormalizationService>.Instance, pathService, toolchainStatus);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateNormalizedTrackAsync_WhenTheUserIdIsEmpty_ShouldReturnNormalizationFailedError()
|
||||
{
|
||||
// Arrange
|
||||
NormalizedTrackRequestDto request = CreateRequest(userId: Guid.Empty);
|
||||
|
||||
// Act
|
||||
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Playback.NormalizationFailed, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)] // The source file length no longer matches the declared delivery.
|
||||
[InlineData(false)] // The source file modification time no longer matches the declared delivery.
|
||||
public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourceFileChangedSinceTheDeliveryWasDeclared_ShouldReturnPlaybackDeliveryChangedError(bool isLengthChanged)
|
||||
{
|
||||
// Arrange
|
||||
NormalizedTrackRequestDto request = CreateRequest(
|
||||
sourceLength: isLengthChanged ? _sourceLength + 1 : _sourceLength,
|
||||
sourceLastModifiedUtc: isLengthChanged ? _sourceLastModifiedUtc : _sourceLastModifiedUtc.AddMinutes(-1));
|
||||
|
||||
// Act
|
||||
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Playback.PlaybackDeliveryChanged, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact(Skip = "Production bug: a missing source file inside an allowed root throws FileNotFoundException from HasReparsePointBelow (File.GetAttributes on the leaf) instead of returning Errors.Music.TrackFileNotFound. The exception escapes GetOrCreateNormalizedTrackAsync, so the contract of the method is violated for a track deleted between the manifest and the first segment request.")]
|
||||
public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourceFileDoesNotExist_ShouldReturnTrackFileNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
NormalizedTrackRequestDto request = CreateRequest(sourcePath: Path.Combine(_sourceRoot, "missing.flac"));
|
||||
|
||||
// Act
|
||||
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourcePathIsOutsideEveryAllowedRoot_ShouldReturnTrackFileNotFoundError()
|
||||
{
|
||||
// Arrange
|
||||
NormalizedTrackRequestDto request = CreateRequest(allowedRoots: [Path.Combine(_sandboxRoot, "other")]);
|
||||
|
||||
// Act
|
||||
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateNormalizedTrackAsync_WhenTheServiceIsDisposed_ShouldReturnNormalizationUnavailableError()
|
||||
{
|
||||
// Arrange
|
||||
NormalizedTrackRequestDto request = CreateRequest();
|
||||
_sut.Dispose();
|
||||
|
||||
// Act
|
||||
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Playback.NormalizationUnavailable, result.FirstError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the service and the temporary directories of the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_sut.Dispose();
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(_sandboxRoot))
|
||||
Directory.Delete(_sandboxRoot, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// A temporary directory that cannot be removed does not fail the test.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a normalization request that matches the source file of the test.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose request starts the production.</param>
|
||||
/// <param name="sourcePath">The file system path of the stored audio file of the track.</param>
|
||||
/// <param name="allowedRoots">The content locations the source path is allowed to be inside.</param>
|
||||
/// <param name="sourceLength">The length the source file had when the delivery was declared, in bytes.</param>
|
||||
/// <param name="sourceLastModifiedUtc">The last modification time the source file had when the delivery was declared.</param>
|
||||
/// <returns>The created request.</returns>
|
||||
private NormalizedTrackRequestDto CreateRequest(
|
||||
Guid? userId = null,
|
||||
string? sourcePath = null,
|
||||
IReadOnlyList<string>? allowedRoots = null,
|
||||
long? sourceLength = null,
|
||||
DateTime? sourceLastModifiedUtc = null)
|
||||
{
|
||||
return _normalizedTrackRequestDtoFixture.Create(
|
||||
trackId: Guid.NewGuid(),
|
||||
userId: userId ?? Guid.NewGuid(),
|
||||
sourcePath: sourcePath ?? _sourcePath,
|
||||
allowedRoots: allowedRoots ?? [_sourceRoot],
|
||||
sourceContainer: "FLAC",
|
||||
mode: PlaybackDeliveryMode.Transcode,
|
||||
container: "MP3",
|
||||
codec: "MP3",
|
||||
segmentDurationSeconds: 6,
|
||||
durationInSeconds: 120,
|
||||
bitrate: 900,
|
||||
sampleRate: 44100,
|
||||
channels: 2,
|
||||
bitDepth: 16,
|
||||
quality: PlaybackStreamingQuality.Auto,
|
||||
sourceLength: sourceLength ?? _sourceLength,
|
||||
sourceLastModifiedUtc: sourceLastModifiedUtc ?? _sourceLastModifiedUtc);
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TranscodingToolchainStatus"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TranscodingToolchainStatusTests
|
||||
{
|
||||
private readonly TranscodingToolchainStatus _sut;
|
||||
private readonly IReadOnlyList<string> _catalogEncoderNames;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TranscodingToolchainStatusTests"/> class.
|
||||
/// </summary>
|
||||
public TranscodingToolchainStatusTests()
|
||||
{
|
||||
_sut = new TranscodingToolchainStatus();
|
||||
_catalogEncoderNames = [.. PlaybackFormatCatalog.Formats.Select(format => format.EncoderName).Distinct(StringComparer.OrdinalIgnoreCase)];
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsTranscoderAvailable_WhenTheStatusIsFresh_ShouldReturnTrue()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.IsTranscoderAvailable;
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsEncoderAvailable_WhenTheStatusIsFresh_ShouldReturnTrueForEveryCatalogEncoder()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<bool> results = [.. _catalogEncoderNames.Select(_sut.IsEncoderAvailable)];
|
||||
|
||||
// Assert
|
||||
Assert.All(results, result => Assert.True(result));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordUnavailable_WhenCalled_ShouldReportTheTranscoderAndEveryCatalogEncoderUnavailable()
|
||||
{
|
||||
// Act
|
||||
_sut.RecordUnavailable();
|
||||
|
||||
// Assert
|
||||
Assert.False(_sut.IsTranscoderAvailable);
|
||||
Assert.All(_catalogEncoderNames, encoderName => Assert.False(_sut.IsEncoderAvailable(encoderName)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordMissingEncoders_WhenCalled_ShouldKeepTheTranscoderAvailableAndReportOnlyTheListedEncodersUnavailable()
|
||||
{
|
||||
// Arrange
|
||||
string missingEncoderName = _catalogEncoderNames[0];
|
||||
string availableEncoderName = _catalogEncoderNames[1];
|
||||
|
||||
// Act
|
||||
_sut.RecordMissingEncoders([missingEncoderName]);
|
||||
|
||||
// Assert
|
||||
Assert.True(_sut.IsTranscoderAvailable);
|
||||
Assert.False(_sut.IsEncoderAvailable(missingEncoderName));
|
||||
Assert.True(_sut.IsEncoderAvailable(availableEncoderName));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("AAC")] // An encoder name in upper case.
|
||||
[InlineData("Aac")] // An encoder name in mixed case.
|
||||
public void RecordMissingEncoders_WhenTheNameDiffersInCase_ShouldReportTheEncoderUnavailable(string missingEncoderName)
|
||||
{
|
||||
// Act
|
||||
_sut.RecordMissingEncoders([missingEncoderName]);
|
||||
|
||||
// Assert
|
||||
Assert.True(_sut.IsTranscoderAvailable);
|
||||
Assert.False(_sut.IsEncoderAvailable("aac"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordMissingEncoders_WhenCalledTwice_ShouldReplaceThePreviousMissingSetInsteadOfAccumulatingIt()
|
||||
{
|
||||
// Act
|
||||
_sut.RecordMissingEncoders(["aac"]);
|
||||
_sut.RecordMissingEncoders(["libopus"]);
|
||||
|
||||
// Assert
|
||||
Assert.True(_sut.IsTranscoderAvailable);
|
||||
Assert.True(_sut.IsEncoderAvailable("aac"));
|
||||
Assert.False(_sut.IsEncoderAvailable("libopus"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordMissingEncoders_WhenTheListIsEmpty_ShouldKeepEveryCatalogEncoderAvailable()
|
||||
{
|
||||
// Act
|
||||
_sut.RecordMissingEncoders([]);
|
||||
|
||||
// Assert
|
||||
Assert.True(_sut.IsTranscoderAvailable);
|
||||
Assert.All(_catalogEncoderNames, encoderName => Assert.True(_sut.IsEncoderAvailable(encoderName)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordAvailable_WhenTheTranscoderWasUnavailable_ShouldRestoreTheTranscoderAndEveryCatalogEncoder()
|
||||
{
|
||||
// Arrange
|
||||
_sut.RecordUnavailable();
|
||||
|
||||
// Act
|
||||
_sut.RecordAvailable();
|
||||
|
||||
// Assert
|
||||
Assert.True(_sut.IsTranscoderAvailable);
|
||||
Assert.All(_catalogEncoderNames, encoderName => Assert.True(_sut.IsEncoderAvailable(encoderName)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordAvailable_WhenEncodersWereMissing_ShouldClearTheMissingSet()
|
||||
{
|
||||
// Arrange
|
||||
_sut.RecordMissingEncoders(["aac", "libopus"]);
|
||||
|
||||
// Act
|
||||
_sut.RecordAvailable();
|
||||
|
||||
// Assert
|
||||
Assert.True(_sut.IsTranscoderAvailable);
|
||||
Assert.True(_sut.IsEncoderAvailable("aac"));
|
||||
Assert.True(_sut.IsEncoderAvailable("libopus"));
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Cancellation;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibrariesScanCancellationTracker"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibrariesScanCancellationTrackerTests
|
||||
{
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void GetTokenForScan_WhenScanWasRegistered_ShouldReturnActiveToken()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
sut.RegisterScan(compositeId);
|
||||
CancellationToken token = sut.GetTokenForScan(compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.False(token.IsCancellationRequested);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetTokenForScan_WhenScanWasNotRegistered_ShouldReturnNone()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
CancellationToken token = sut.GetTokenForScan(compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(CancellationToken.None, token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CancelScan_WhenScanWasRegistered_ShouldCancelItsTokenAndRemoveTheScan()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
sut.RegisterScan(compositeId);
|
||||
CancellationToken token = sut.GetTokenForScan(compositeId);
|
||||
|
||||
// Act
|
||||
sut.CancelScan(compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.True(token.IsCancellationRequested);
|
||||
Assert.Equal(CancellationToken.None, sut.GetTokenForScan(compositeId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveScan_WhenScanWasRegistered_ShouldCancelItsTokenAndRemoveTheScan()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
sut.RegisterScan(compositeId);
|
||||
CancellationToken token = sut.GetTokenForScan(compositeId);
|
||||
|
||||
// Act
|
||||
sut.RemoveScan(compositeId);
|
||||
|
||||
// Assert
|
||||
Assert.True(token.IsCancellationRequested);
|
||||
Assert.Equal(CancellationToken.None, sut.GetTokenForScan(compositeId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CancelScan_WhenScanWasNotRegistered_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Action act = () => sut.CancelScan(compositeId);
|
||||
|
||||
// Assert
|
||||
act();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_ShouldCancelAllRegisteredScans()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibrariesScanCancellationTracker sut = new();
|
||||
MediaLibraryScanCompositeId firstCompositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanCompositeId secondCompositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
sut.RegisterScan(firstCompositeId);
|
||||
sut.RegisterScan(secondCompositeId);
|
||||
CancellationToken firstToken = sut.GetTokenForScan(firstCompositeId);
|
||||
CancellationToken secondToken = sut.GetTokenForScan(secondCompositeId);
|
||||
|
||||
// Act
|
||||
sut.Dispose();
|
||||
|
||||
// Assert
|
||||
Assert.True(firstToken.IsCancellationRequested);
|
||||
Assert.True(secondToken.IsCancellationRequested);
|
||||
}
|
||||
}
|
||||
+466
@@ -0,0 +1,466 @@
|
||||
#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 Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
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 SECOND_AUDIO_FILE_PATH = @"C:\Music\other.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 ILogger<MusicFileSystemDiscoveryJob> _mockLogger;
|
||||
private readonly MusicFileSystemDiscoveryJob _sut;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = 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();
|
||||
_mockLogger = Substitute.For<ILogger<MusicFileSystemDiscoveryJob>>();
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
_sut = new MusicFileSystemDiscoveryJob(_mockServiceScopeFactory, _mockLogger)
|
||||
{
|
||||
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);
|
||||
_mockFileProviderService.Received(1).GetFilePaths(Arg.Any<FileSystemPathId>(), true);
|
||||
_mockDirectoryProviderService.Received(1).GetSubdirectoryPaths(Arg.Any<FileSystemPathId>(), true);
|
||||
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_WhenTheLibraryIsOnSsd_ShouldReadInParallelAndSkipFilesThatBecomeInaccessible()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(isContentOnSsd: true);
|
||||
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH, SECOND_AUDIO_FILE_PATH, IMAGE_FILE_PATH], subdirectories: []);
|
||||
_mockFileProviderService.GetSize(Arg.Is<FileSystemPathId>(path => path.Path == AUDIO_FILE_PATH))
|
||||
.Returns(_ => throw new IOException("The file vanished between enumeration and processing"));
|
||||
_mockFileProviderService.GetSize(Arg.Is<FileSystemPathId>(path => path.Path == SECOND_AUDIO_FILE_PATH)).Returns(Result.From<long?>(1234L));
|
||||
_mockFileProviderService.GetLastWriteTime(Arg.Is<FileSystemPathId>(path => path.Path == SECOND_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
|
||||
// The sequential path does not catch per-file IO exceptions, so completing here proves the parallel path was taken.
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1
|
||||
&& entities.First().Path == SECOND_AUDIO_FILE_PATH
|
||||
&& entities.First().Size == 1234
|
||||
&& entities.First().LibraryScanId == _scanId.Value
|
||||
&& entities.First().NeedsRehash),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Debug,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(state => state.ToString()!.Contains("solid state drive", StringComparison.Ordinal)),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(state => state.ToString()!.Contains(AUDIO_FILE_PATH, StringComparison.Ordinal)),
|
||||
Arg.Any<IOException>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHiddenFilesAndDirectoriesAreSkipped_ShouldAskTheProvidersToExcludeThem()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(shouldSkipHiddenFilesAndDirectoriesDuringScan: true);
|
||||
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: [], shouldIncludeHiddenElements: false);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
_mockFileProviderService.Received(1).GetFilePaths(Arg.Any<FileSystemPathId>(), false);
|
||||
_mockDirectoryProviderService.Received(1).GetSubdirectoryPaths(Arg.Any<FileSystemPathId>(), false);
|
||||
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_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] = _directoryScanFingerprintEntityFixture.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] = _directoryScanFingerprintEntityFixture.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_WhenAFileMetadataReadThrowsAnUnexpectedException_ShouldMarkJobAsFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(isContentOnSsd: true);
|
||||
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []);
|
||||
_mockFileProviderService.GetSize(Arg.Any<FileSystemPathId>()).Returns(_ => throw new InvalidOperationException("Unexpected defect"));
|
||||
|
||||
// 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>
|
||||
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Whether the library skips hidden files and directories.</param>
|
||||
/// <param name="isContentOnSsd">Whether the content of the library is stored on a solid state drive.</param>
|
||||
private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false, bool shouldSkipHiddenFilesAndDirectoriesDuringScan = false, bool isContentOnSsd = false)
|
||||
{
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Music,
|
||||
contentLocations: [ROOT_PATH],
|
||||
shouldSkipUnchangedDirectoriesDuringScan: shouldSkipUnchangedDirectoriesDuringScan,
|
||||
shouldSkipHiddenFilesAndDirectoriesDuringScan: shouldSkipHiddenFilesAndDirectoriesDuringScan,
|
||||
isContentOnSsd: isContentOnSsd);
|
||||
_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>
|
||||
/// <param name="shouldIncludeHiddenElements">Whether the providers are expected to include hidden elements.</param>
|
||||
private void SetupDirectory(string directory, string[] files, string[] subdirectories, bool shouldIncludeHiddenElements = true)
|
||||
{
|
||||
_mockFileProviderService.GetFilePaths(Arg.Is<FileSystemPathId>(path => path.Path == directory), shouldIncludeHiddenElements)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([.. files.Select(file => PathId(file))]));
|
||||
_mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Is<FileSystemPathId>(path => path.Path == directory), shouldIncludeHiddenElements)
|
||||
.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;
|
||||
}
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
using NSubstitute;
|
||||
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 readonly IPathService _mockPathService;
|
||||
private readonly MusicLibraryPathStructure _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicLibraryPathStructureTests"/> class.
|
||||
/// </summary>
|
||||
public MusicLibraryPathStructureTests()
|
||||
{
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_sut = new MusicLibraryPathStructure(_mockPathService);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\', @"C:\Music\Queen\A Night at the Opera", @"C:\Music\Queen\A Night at the Opera\Bohemian Rhapsody.flac")] // Windows separated path.
|
||||
[InlineData('/', "/music/queen/a-night-at-the-opera", "/music/queen/a-night-at-the-opera/bohemian-rhapsody.flac")] // Unix separated path.
|
||||
public void GetAlbumDirectory_WhenTheTrackIsInTheAlbumDirectory_ShouldReturnTheTrackDirectory(char separator, string albumDirectory, string trackPath)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.PathSeparator.Returns(separator);
|
||||
|
||||
// Act
|
||||
string result = _sut.GetAlbumDirectory(trackPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(albumDirectory, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\', "Disc 1")] // Canonical disc directory name, Windows separated path.
|
||||
[InlineData('\\', "disc 2")] // Lowercase disc directory name, Windows separated path.
|
||||
[InlineData('\\', "CD3")] // Compact disc directory name, Windows separated path.
|
||||
[InlineData('\\', "disk4")] // Disk directory name, Windows separated path.
|
||||
[InlineData('/', "Disc 1")] // Canonical disc directory name, Unix separated path.
|
||||
[InlineData('/', "disc 2")] // Lowercase disc directory name, Unix separated path.
|
||||
[InlineData('/', "CD3")] // Compact disc directory name, Unix separated path.
|
||||
[InlineData('/', "disk4")] // Disk directory name, Unix separated path.
|
||||
public void GetAlbumDirectory_WhenTheTrackIsInADiscDirectory_ShouldReturnTheParentAlbumDirectory(char separator, string discDirectoryName)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.PathSeparator.Returns(separator);
|
||||
string albumDirectory = string.Join(separator, "music", "queen", "a-night-at-the-opera");
|
||||
string trackPath = string.Join(separator, albumDirectory, discDirectoryName, "bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
string result = _sut.GetAlbumDirectory(trackPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(albumDirectory, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\')] // Windows separated path.
|
||||
[InlineData('/')] // Unix separated path.
|
||||
public void GetAlbumDirectory_WhenTheDirectoryIsNotADiscDirectory_ShouldReturnTheTrackDirectory(char separator)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.PathSeparator.Returns(separator);
|
||||
string albumDirectory = string.Join(separator, "music", "queen", "live");
|
||||
string trackPath = string.Join(separator, albumDirectory, "bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
string result = _sut.GetAlbumDirectory(trackPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(albumDirectory, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAlbumDirectory_WhenThePathIsNullOrEmpty_ShouldReturnTheProvidedPath()
|
||||
{
|
||||
// Act
|
||||
string nullResult = _sut.GetAlbumDirectory(null!);
|
||||
string emptyResult = _sut.GetAlbumDirectory(string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Null(nullResult);
|
||||
Assert.Equal(string.Empty, emptyResult);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\')] // Windows separated path.
|
||||
[InlineData('/')] // Unix separated path.
|
||||
public void GetAlbumDirectory_WhenThePathHasNoDirectory_ShouldReturnTheProvidedPath(char separator)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.PathSeparator.Returns(separator);
|
||||
const string FILE_NAME_ONLY = "Bohemian Rhapsody.flac";
|
||||
|
||||
// Act
|
||||
string result = _sut.GetAlbumDirectory(FILE_NAME_ONLY);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(FILE_NAME_ONLY, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\', "Album")] // Canonical release type directory, Windows separated path.
|
||||
[InlineData('\\', "album")] // Lowercase release type directory, Windows separated path.
|
||||
[InlineData('/', "Album")] // Canonical release type directory, Unix separated path.
|
||||
[InlineData('/', "album")] // Lowercase release type directory, Unix separated path.
|
||||
public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsAReleaseType_ShouldReturnIt(char separator, string releaseTypeDirectoryName)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.PathSeparator.Returns(separator);
|
||||
string trackPath = string.Join(separator, "music", "queen", releaseTypeDirectoryName, "a-night-at-the-opera", "bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
string? result = _sut.GetReleaseTypeDirectoryName(trackPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(releaseTypeDirectoryName, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\')] // Windows separated path.
|
||||
[InlineData('/')] // Unix separated path.
|
||||
public void GetReleaseTypeDirectoryName_WhenTheAlbumIsMultiDisc_ShouldReturnTheReleaseTypeDirectory(char separator)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.PathSeparator.Returns(separator);
|
||||
string trackPath = string.Join(separator, "music", "queen", "Album", "a-night-at-the-opera", "Disc 1", "bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
string? result = _sut.GetReleaseTypeDirectoryName(trackPath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Album", result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\')] // Windows separated path.
|
||||
[InlineData('/')] // Unix separated path.
|
||||
public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsNotAReleaseType_ShouldReturnNull(char separator)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.PathSeparator.Returns(separator);
|
||||
string trackPath = string.Join(separator, "music", "queen", "a-night-at-the-opera", "bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
string? result = _sut.GetReleaseTypeDirectoryName(trackPath);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\', "Live")] // Release type name used as the artist directory name, Windows separated path.
|
||||
[InlineData('/', "Live")] // Release type name used as the artist directory name, Unix separated path.
|
||||
[InlineData('\\', "42")] // Numeric artist directory name, Windows separated path.
|
||||
[InlineData('/', "42")] // Numeric artist directory name, Unix separated path.
|
||||
public void GetReleaseTypeDirectoryName_WhenTheArtistDirectoryIsNamedLikeAReleaseType_ShouldReturnNull(char separator, string artistName)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.PathSeparator.Returns(separator);
|
||||
// The library uses no release type directory, so the parent of the album directory is the artist directory.
|
||||
string trackPath = string.Join(separator, "music", artistName, "a-night-at-the-opera", "bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
string? result = _sut.GetReleaseTypeDirectoryName(trackPath, artistName);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData('\\')] // Windows separated path.
|
||||
[InlineData('/')] // Unix separated path.
|
||||
public void GetReleaseTypeDirectoryName_WhenAReleaseTypeDirectoryDiffersFromTheArtistDirectory_ShouldReturnIt(char separator)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.PathSeparator.Returns(separator);
|
||||
string trackPath = string.Join(separator, "music", "Queen", "Live", "a-night-at-the-opera", "bohemian-rhapsody.flac");
|
||||
|
||||
// Act
|
||||
string? result = _sut.GetReleaseTypeDirectoryName(trackPath, "Queen");
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Live", result);
|
||||
}
|
||||
}
|
||||
+619
@@ -0,0 +1,619 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicMediaLibraryScanArtworkEnricher"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicMediaLibraryScanArtworkEnricherTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository;
|
||||
private readonly IArtistRepository _mockArtistRepository;
|
||||
private readonly IAlbumRepository _mockAlbumRepository;
|
||||
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
|
||||
private readonly IUserSettingsRepository _mockUserSettingsRepository;
|
||||
private readonly IMusicArtworkService _mockMusicArtworkService;
|
||||
private readonly IFileHashService _mockFileHashService;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly TestArtworkProvider<ArtistMetadataLookupDto> _artistProvider;
|
||||
private readonly TestArtworkProvider<AlbumMetadataLookupDto> _albumProvider;
|
||||
private readonly MusicMediaLibraryScanArtworkEnricher _sut;
|
||||
private readonly ServiceProvider _serviceProvider;
|
||||
private readonly Guid _artistPluginId = Guid.NewGuid();
|
||||
private readonly Guid _albumPluginId = Guid.NewGuid();
|
||||
private readonly LibraryId _libraryId;
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicMediaLibraryScanArtworkEnricherTests"/> class.
|
||||
/// </summary>
|
||||
public MusicMediaLibraryScanArtworkEnricherTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockArtworkProviderConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockArtistRepository = Substitute.For<IArtistRepository>();
|
||||
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
|
||||
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
|
||||
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository);
|
||||
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
|
||||
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
|
||||
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
|
||||
|
||||
_artistProvider = new TestArtworkProvider<ArtistMetadataLookupDto> { Name = "Artist Provider", RequiresWebAccess = false };
|
||||
_albumProvider = new TestArtworkProvider<AlbumMetadataLookupDto> { Name = "Album Provider", RequiresWebAccess = false };
|
||||
|
||||
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
|
||||
_mockFileHashService = Substitute.For<IFileHashService>();
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('/');
|
||||
|
||||
// The enricher resolves the keyed artwork providers from the scope of the service provider, and specializes them by the lookup they accept,
|
||||
// so a real container is used to honor the keyed registration of the typed providers.
|
||||
ServiceCollection services = new();
|
||||
services.AddScoped<IUnitOfWork>(_ => _mockUnitOfWork);
|
||||
services.AddScoped<IDomainEventPublisher>(_ => _mockDomainEventPublisher);
|
||||
services.AddSingleton(_mockMusicArtworkService);
|
||||
services.AddSingleton(_mockFileHashService);
|
||||
services.AddKeyedSingleton<IArtworkProvider>(_artistPluginId, _artistProvider);
|
||||
services.AddKeyedSingleton<IArtworkProvider>(_albumPluginId, _albumProvider);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
_sut = new MusicMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), NullLogger<MusicMediaLibraryScanArtworkEnricher>.Instance, new MusicLibraryPathStructure(_mockPathService));
|
||||
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
|
||||
// Default stubs that keep the happy path working, overridden per test where needed.
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<UserSettingsEntity?>.Success(null));
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(0));
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ArtistEntity>>([]));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(0));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([]));
|
||||
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string>>(new Dictionary<Guid, string>()));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
SetupSuccessArtworkStorage();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryType_WhenCalled_ShouldReturnMusic()
|
||||
{
|
||||
// Act
|
||||
LibraryType result = _sut.SupportedLibraryType;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryType.Music, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Provider.Error", "Failed to read the configurations"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloads_ShouldSkipProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(canDownloadMetadataFromWeb: false);
|
||||
_artistProvider.RequiresWebAccess = true;
|
||||
_albumProvider.RequiresWebAccess = true;
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloadsButTheProviderIsLocal_ShouldStillResolve()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(canDownloadMetadataFromWeb: false);
|
||||
_artistProvider.RequiresWebAccess = true;
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupAlbums(album);
|
||||
_albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1, _albumProvider.CallCount);
|
||||
Assert.Equal(0, _artistProvider.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheArtistProviderReturnsArtwork_ShouldStoreAndPersistEnrichedArtistArtwork()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync(
|
||||
_libraryId.Value,
|
||||
Arg.Any<string>(),
|
||||
artist.Id,
|
||||
artist.Name,
|
||||
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artist.Id, Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
|
||||
&& entities.First().OwnerType == MusicArtworkOwnerType.Artist
|
||||
&& entities.First().OwnerId == artist.Id
|
||||
&& entities.First().ArtworkType == ArtworkType.Cover
|
||||
&& entities.First().Ordinal == 0
|
||||
&& entities.First().Status == ArtworkStatus.Enriched
|
||||
&& entities.First().Provider == "Artist Provider"
|
||||
&& entities.First().FileName == "/media/music/cover.jpg"
|
||||
&& entities.First().ContentHash == 123UL),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumProviderReturnsArtwork_ShouldStoreAndPersistEnrichedAlbumArtwork()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupAlbums(album);
|
||||
_albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
|
||||
_libraryId.Value,
|
||||
album.Id,
|
||||
Arg.Any<string>(),
|
||||
album.ArtistId,
|
||||
Arg.Any<string>(),
|
||||
album.Title,
|
||||
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, album.Id, Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
|
||||
&& entities.First().OwnerType == MusicArtworkOwnerType.Album
|
||||
&& entities.First().OwnerId == album.Id
|
||||
&& entities.First().Status == ArtworkStatus.Enriched
|
||||
&& entities.First().Provider == "Album Provider"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheProviderAnswersWithNoArtwork_ShouldMarkTheArtistNotAvailable()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
|
||||
&& entities.First().Status == ArtworkStatus.NotAvailable
|
||||
&& entities.First().FileName == null
|
||||
&& entities.First().Provider == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheArtistFailed()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromException<IReadOnlyList<ArtworkDto>>(new HttpRequestException("Transient failure."));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheArtistFailed()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Artwork.Error", "Failed to store the artwork"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenClearingTheStoredArtworkFilesFails_ShouldClearTheStoredArtworkRecordsAndMarkTheArtistFailed()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>())
|
||||
.Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork files"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artist.Id, Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
|
||||
&& entities.First().OwnerType == MusicArtworkOwnerType.Artist
|
||||
&& entities.First().OwnerId == artist.Id
|
||||
&& entities.First().Status == ArtworkStatus.Failed
|
||||
&& entities.First().FileName == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenClearingTheStoredArtworkRecordsFails_ShouldLeaveTheArtistUnresolved()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork records"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumHasNoMusicBrainzIdentifierAndNoLocalProvider_ShouldLeaveItUnresolved()
|
||||
{
|
||||
// Arrange
|
||||
_albumProvider.RequiresWebAccess = true;
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
libraryId: _libraryId.Value,
|
||||
includeMusicBrainzReleaseId: false,
|
||||
includeMusicBrainzReleaseGroupId: false);
|
||||
SetupAlbums(album);
|
||||
_albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(0, _albumProvider.CallCount);
|
||||
await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumCountCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to count the albums"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumsPageCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to read the albums"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheTrackPathsCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
|
||||
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to read the track paths"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to save the changes"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the media library reader with a library owned by the test user.
|
||||
/// </summary>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the library allows downloading data from the web.</param>
|
||||
private void SetupLibrary(bool canDownloadMetadataFromWeb = true)
|
||||
{
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Music,
|
||||
canDownloadMetadataFromWeb: canDownloadMetadataFromWeb);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork provider configuration reader with one enabled configuration per test plugin.
|
||||
/// </summary>
|
||||
private void SetupConfiguration()
|
||||
{
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(
|
||||
[
|
||||
_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, _artistPluginId, 0),
|
||||
_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, _albumPluginId, 1)
|
||||
]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artist reader with a single page holding the provided artists.
|
||||
/// </summary>
|
||||
/// <param name="artists">The artists of the page.</param>
|
||||
private void SetupArtists(params ArtistEntity[] artists)
|
||||
{
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(artists.Length));
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<ArtistEntity>>(artists),
|
||||
Result.From<IReadOnlyList<ArtistEntity>>([]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the album reader with a single page holding the provided albums.
|
||||
/// </summary>
|
||||
/// <param name="albums">The albums of the page.</param>
|
||||
private void SetupAlbums(params AlbumEntity[] albums)
|
||||
{
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(albums.Length));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<AlbumEntity>>(albums),
|
||||
Result.From<IReadOnlyList<AlbumEntity>>([]));
|
||||
Dictionary<Guid, string> trackPaths = albums.ToDictionary(album => album.Id, album => "/music/artist/album/track.flac");
|
||||
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string>>(trackPaths));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork storage and persistence so that an item is stored successfully.
|
||||
/// </summary>
|
||||
private void SetupSuccessArtworkStorage()
|
||||
{
|
||||
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/music/cover.jpg"));
|
||||
_mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/music/cover.jpg"));
|
||||
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>()).Returns(Result.Deleted);
|
||||
_mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>()).Returns(Result.Deleted);
|
||||
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
|
||||
_mockMusicArtworkRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
_mockFileHashService.ComputeFileHash(Arg.Any<string>()).Returns(123UL);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deterministic artwork provider for a specific lookup type, used instead of a substitute because the default implementation of
|
||||
/// <see cref="IArtworkProvider.GetArtworkAsync(MetadataLookupDto, CancellationToken)"/> cannot be intercepted reliably.
|
||||
/// </summary>
|
||||
/// <typeparam name="TLookup">The type of the lookup the provider accepts.</typeparam>
|
||||
private sealed class TestArtworkProvider<TLookup> : IArtworkProvider<TLookup> where TLookup : MetadataLookupDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the display name of the artwork provider.
|
||||
/// </summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the media library types this artwork provider supports.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes { get; set; } = [LibraryType.Music];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
|
||||
/// </summary>
|
||||
public bool RequiresWebAccess { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the callback that supplies the artwork of a media item.
|
||||
/// </summary>
|
||||
public Func<TLookup, CancellationToken, Task<IReadOnlyList<ArtworkDto>>> OnGetArtworkAsync { get; set; } = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of times the provider was asked for artwork.
|
||||
/// </summary>
|
||||
public int CallCount { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artworks of the media item described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to get the artwork for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artworks of the media item, or an empty collection when no artwork was found.</returns>
|
||||
public Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
CallCount++;
|
||||
return OnGetArtworkAsync(lookup, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
#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.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
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 IPathService _mockPathService;
|
||||
private readonly MusicMediaLibraryScanItemMaterializer _sut;
|
||||
private readonly MusicLibraryScanItemMetadataEntityFixture _musicLibraryScanItemMetadataEntityFixture = 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.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Deleted);
|
||||
_mockStagedMetadataRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([]));
|
||||
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('/');
|
||||
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("track");
|
||||
|
||||
_sut = new MusicMediaLibraryScanItemMaterializer(new MusicLibraryPathStructure(_mockPathService), _mockPathService);
|
||||
}
|
||||
|
||||
[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 = _musicLibraryScanItemMetadataEntityFixture.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 = _musicLibraryScanItemMetadataEntityFixture.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.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(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);
|
||||
// The container read from the file itself is carried from the staged metadata to the materialized track.
|
||||
Assert.Equal(firstStagedItem.Container, Assert.Single(firstAlbum.Tracks).Container);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenTheStagedItemHasNoContainer_ShouldMaterializeTheTrackWithoutAContainer()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryScanItemMetadataEntity stagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Some Artist",
|
||||
releaseName: "Some Release",
|
||||
path: "/music/some-artist/some-release/track.mp3",
|
||||
includeMusicBrainzTags: false,
|
||||
includeContainer: false);
|
||||
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([stagedItem]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(stagedItem.Path), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
ArtistEntity artist = Assert.Single(_insertedArtists);
|
||||
AlbumEntity album = Assert.Single(artist.Albums);
|
||||
// A file whose container the scan could not recognize materializes its track without a container, rather than failing the scan.
|
||||
Assert.Null(Assert.Single(album.Tracks).Container);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenCompilationTracksHaveDifferentTrackArtists_ShouldMaterializeASingleAlbumArtist()
|
||||
{
|
||||
// Arrange
|
||||
Guid variousArtistsId = Guid.NewGuid();
|
||||
Guid compilationReleaseId = Guid.NewGuid();
|
||||
MusicLibraryScanItemMetadataEntity firstStagedItem = _musicLibraryScanItemMetadataEntityFixture.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 = _musicLibraryScanItemMetadataEntityFixture.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.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(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 = _musicLibraryScanItemMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Shared Artist Name",
|
||||
releaseName: "Shared Release Title",
|
||||
path: "/music/shared-artist/shared-release/first.mp3",
|
||||
includeMusicBrainzTags: false);
|
||||
MusicLibraryScanItemMetadataEntity secondStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Shared Artist Name",
|
||||
releaseName: "Shared Release Title",
|
||||
path: "/music/shared-artist/shared-release/second.mp3",
|
||||
includeMusicBrainzTags: false);
|
||||
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenTheCurrentScanStagedNothing_ShouldMaterializeTheMetadataLeftBehindByAnEarlierScanForTheCurrentSnapshotPaths()
|
||||
{
|
||||
// Arrange
|
||||
MusicLibraryScanItemMetadataEntity stagedItemInSnapshot = _musicLibraryScanItemMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Recovered Artist",
|
||||
releaseName: "Recovered Release",
|
||||
path: "/music/recovered-artist/recovered-release/first.mp3",
|
||||
includeMusicBrainzTags: false);
|
||||
MusicLibraryScanItemMetadataEntity stagedItemNoLongerInSnapshot = _musicLibraryScanItemMetadataEntityFixture.Create(
|
||||
libraryId: _libraryId,
|
||||
artistName: "Deleted Artist",
|
||||
releaseName: "Deleted Release",
|
||||
path: "/music/deleted-artist/deleted-release/deleted.mp3",
|
||||
includeMusicBrainzTags: false);
|
||||
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([stagedItemInSnapshot, stagedItemNoLongerInSnapshot]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(stagedItemInSnapshot.Path), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsSuccess);
|
||||
// The metadata left behind by the earlier scan is reused only for the files that are still in the current snapshot.
|
||||
ArtistEntity artist = Assert.Single(_insertedArtists);
|
||||
Assert.Equal("Recovered Artist", artist.Name);
|
||||
AlbumEntity album = Assert.Single(artist.Albums);
|
||||
Assert.Equal(stagedItemInSnapshot.Path, Assert.Single(album.Tracks).Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearStagedDataAsync_WhenCalled_ShouldDeleteTheStagedMetadataOfTheWholeLibrary()
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.ClearStagedDataAsync(_mockUnitOfWork, _libraryId, _scanId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
await _mockStagedMetadataRepository.Received(1).DeleteByLibraryIdAsync(_libraryId, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the set of media library scan snapshot paths that the media library scan produces.
|
||||
/// </summary>
|
||||
/// <param name="paths">The paths of the set.</param>
|
||||
/// <returns>The set of paths.</returns>
|
||||
private static IReadOnlySet<string> CreatePathSet(params string[] paths)
|
||||
{
|
||||
return new HashSet<string>(paths, StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
+326
@@ -0,0 +1,326 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.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="MusicMediaLibraryScanMetadataEnricher"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicMediaLibraryScanMetadataEnricherTests
|
||||
{
|
||||
private const string PROVIDER_A_NAME = "ProviderA";
|
||||
private const string PROVIDER_B_NAME = "ProviderB";
|
||||
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtistRepository _mockArtistRepository;
|
||||
private readonly IAlbumRepository _mockAlbumRepository;
|
||||
private readonly ITrackRepository _mockTrackRepository;
|
||||
private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository;
|
||||
private readonly IUserSettingsRepository _mockUserSettingsRepository;
|
||||
private readonly IMetadataProvider _mockProviderA;
|
||||
private readonly IMetadataProvider _mockProviderB;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ServiceProvider _serviceProvider;
|
||||
private readonly MusicMediaLibraryScanMetadataEnricher _sut;
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly ArtistMetadataDtoFixture _artistMetadataDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = 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="MusicMediaLibraryScanMetadataEnricherTests"/> class.
|
||||
/// </summary>
|
||||
public MusicMediaLibraryScanMetadataEnricherTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockArtistRepository = Substitute.For<IArtistRepository>();
|
||||
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
|
||||
_mockTrackRepository = Substitute.For<ITrackRepository>();
|
||||
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
|
||||
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
|
||||
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
|
||||
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository);
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(Substitute.For<IMediaContributorRepository>());
|
||||
|
||||
// Both plugins expose only an artist metadata provider, so that the tests exercise the artist lookup in isolation, without album or track lookups ever reaching a provider.
|
||||
_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(
|
||||
[
|
||||
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginAId, rank: 1),
|
||||
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginBId, rank: 2)
|
||||
]));
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddScoped<IUnitOfWork>(_ => _mockUnitOfWork);
|
||||
services.AddScoped<IDomainEventPublisher>(_ => _mockDomainEventPublisher);
|
||||
services.AddKeyedTransient<IMetadataProvider>(pluginAId, (serviceProvider, serviceKey) => _mockProviderA);
|
||||
services.AddKeyedTransient<IMetadataProvider>(pluginBId, (serviceProvider, serviceKey) => _mockProviderB);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
_sut = new MusicMediaLibraryScanMetadataEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), NullLogger<MusicMediaLibraryScanMetadataEnricher>.Instance);
|
||||
|
||||
_mockArtistRepository.GetArtistsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<int>.Success(1));
|
||||
_mockAlbumRepository.GetAlbumsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<int>.Success(1));
|
||||
_mockTrackRepository.GetTracksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<int>.Success(1));
|
||||
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([]));
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Success));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenArtistsAlbumsAndTracksNeedEnrichment_ShouldPublishProgressMeasuredInItems()
|
||||
{
|
||||
// Arrange
|
||||
_mockArtistRepository.GetArtistsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<int>.Success(2));
|
||||
_mockAlbumRepository.GetAlbumsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<int>.Success(3));
|
||||
_mockTrackRepository.GetTracksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result<int>.Success(5));
|
||||
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The total is the sum of the artists, the albums and the tracks, and the final update reaches it.
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanJobProgressChangedDomainEvent>(domainEvent =>
|
||||
domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.Progress.CompletedItems == 0
|
||||
&& domainEvent.Progress.TotalItems == 10), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanJobProgressChangedDomainEvent>(domainEvent =>
|
||||
domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.Progress.CompletedItems == 10
|
||||
&& domainEvent.Progress.TotalItems == 10), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheFirstProviderReturnsApplicableMetadata_ShouldNotQueryTheFollowingProviders()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([artist]), Result<IReadOnlyList<ArtistEntity>>.Success([]));
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist"));
|
||||
|
||||
// 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>());
|
||||
await _mockArtistRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ArtistEntity>(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == PROVIDER_A_NAME),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheFirstProviderReturnsNoUsableMetadata_ShouldQueryTheFollowingProviders()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([artist]), Result<IReadOnlyList<ArtistEntity>>.Success([]));
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)null);
|
||||
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Remote Artist"));
|
||||
|
||||
// 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>());
|
||||
await _mockArtistRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ArtistEntity>(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == PROVIDER_B_NAME),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheMetadataOfTheFirstProviderCannotBeApplied_ShouldQueryTheFollowingProviders()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([artist]), Result<IReadOnlyList<ArtistEntity>>.Success([]));
|
||||
// A genre without a name is usable as metadata, but makes the domain conversion of the whole metadata fail.
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist", genres: [_genreDtoFixture.Create(includeName: false)]));
|
||||
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Remote Artist"));
|
||||
|
||||
// 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>());
|
||||
await _mockArtistRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ArtistEntity>(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == PROVIDER_B_NAME),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenSavingFailsWithAUniqueConstraintViolation_ShouldContinueWithTheFollowingArtists()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity firstArtist = _artistEntityFixture.Create(libraryId: _libraryId.Value, name: "First Artist");
|
||||
ArtistEntity secondArtist = _artistEntityFixture.Create(libraryId: _libraryId.Value, name: "Second Artist");
|
||||
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([firstArtist, secondArtist]), Result<IReadOnlyList<ArtistEntity>>.Success([]));
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist"));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result<Success>.Failure(Errors.Persistence.UniqueConstraintViolation), Result.From(Result.Success));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The first artist's save fails with a unique constraint conflict, which must not abort the scan, so the second artist is still processed.
|
||||
await _mockUnitOfWork.Received(2).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockArtistRepository.Received(2).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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)));
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([artist]), Result<IReadOnlyList<ArtistEntity>>.Success([]));
|
||||
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist"));
|
||||
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Remote Artist"));
|
||||
|
||||
// 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>());
|
||||
await _mockArtistRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<ArtistEntity>(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == $"{PROVIDER_A_NAME}, {PROVIDER_B_NAME}"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the provided substitute metadata provider so that it declares the artist lookup type for the music 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(new List<LibraryType> { LibraryType.Music });
|
||||
metadataProvider.RequiresWebAccess.Returns(false);
|
||||
metadataProvider.LookupType.Returns(typeof(ArtistMetadataLookupDto));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an artist metadata that is usable and carries only a name, and optionally a set of genres.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <param name="genres">The optional genres of the artist.</param>
|
||||
/// <returns>The created artist metadata.</returns>
|
||||
private ArtistMetadataDto CreateApplicableArtistMetadata(string name, List<GenreDto>? genres = null)
|
||||
{
|
||||
return _artistMetadataDtoFixture.Create(
|
||||
name: name,
|
||||
genres: genres,
|
||||
includeSortName: false,
|
||||
includeDisambiguation: false,
|
||||
includeType: false,
|
||||
includeGender: false,
|
||||
includeCountry: false,
|
||||
includeArea: false,
|
||||
includeBeginArea: false,
|
||||
includeEndArea: false,
|
||||
includeLifeSpanBegin: false,
|
||||
includeLifeSpanEnd: false,
|
||||
includeWebsite: false,
|
||||
includeMusicBrainzArtistId: false,
|
||||
includeIpis: false,
|
||||
includeIsnis: false,
|
||||
includeGenres: genres is not null,
|
||||
includeTags: false,
|
||||
includeAliases: false,
|
||||
includeRatings: false,
|
||||
includeContributors: false);
|
||||
}
|
||||
}
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
#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));
|
||||
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("Bohemian Rhapsody");
|
||||
_mockPathService.GetFileName(Arg.Any<string>()).Returns("Bohemian Rhapsody.mp3");
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
#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.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanArtworkEnrichmentJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanArtworkEnrichmentJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMediaLibraryScanArtworkEnricher _mockArtworkEnricher;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MediaLibraryScanArtworkEnrichmentJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanArtworkEnrichmentJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanArtworkEnrichmentJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
// The job resolves the artwork enricher of the loaded library type from the service scope, so the music enricher must be available.
|
||||
_mockArtworkEnricher = Substitute.For<IMediaLibraryScanArtworkEnricher>();
|
||||
_mockArtworkEnricher.SupportedLibraryType.Returns(LibraryType.Music);
|
||||
_mockArtworkEnricher.EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanArtworkEnricher>))
|
||||
.Returns(new IMediaLibraryScanArtworkEnricher[] { _mockArtworkEnricher });
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenEnrichmentSucceeds_ShouldPublishProgressChangedEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Music);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtworkEnricher.Received(1).EnrichAsync(_libraryId, _scanId, _userId, Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_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);
|
||||
await _mockArtworkEnricher.DidNotReceive().EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.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.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanDiffJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanDiffJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MediaLibraryScanDiffJob _sut;
|
||||
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="MediaLibraryScanDiffJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanDiffJobTests()
|
||||
{
|
||||
_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);
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanDiffJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMarkingChangesSucceeds_ShouldCompleteAndPublishProgress()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockStagingResultsRepository.Received(1).MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenMarkingChangesFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to mark the changes against the snapshot"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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_WhenMarkingChangesSucceeds_ShouldExecuteTheChildJobs()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
|
||||
_sut.AddChild(mockChild);
|
||||
Guid id = Guid.NewGuid();
|
||||
object input = new();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(id, input, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await mockChild.Received(1).ExecuteAsync(id, input, Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+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.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
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.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
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.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanHashJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanHashJobTests
|
||||
{
|
||||
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 IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly IFileHashService _mockFileHashService;
|
||||
private readonly MediaLibraryScanHashJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanHashJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanHashJobTests()
|
||||
{
|
||||
_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>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_mockFileHashService = Substitute.For<IFileHashService>();
|
||||
_mockServiceProvider.GetService(typeof(IFileHashService)).Returns(_mockFileHashService);
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanHashJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, userId: _userId.Value, isContentOnSsd: true)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFilesNeedHashing_ShouldHashAndPersistThemAndComplete()
|
||||
{
|
||||
// Arrange
|
||||
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf"), _hashedFileSystemFileDtoFixture.Create(path: "/books/book2.pdf")];
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(2));
|
||||
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
|
||||
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
|
||||
.Select(file => file with { CurrentHash = 42UL })
|
||||
.ToList()));
|
||||
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockFileHashService.Received(1).HashFilesAsync(
|
||||
Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(),
|
||||
Arg.Is<bool>(shouldParallelizeReads => shouldParallelizeReads),
|
||||
Arg.Any<Func<Task>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockStagingResultsRepository.Received(1).UpdateFileHashesAsync(
|
||||
_scanId.Value,
|
||||
Arg.Is<IReadOnlyCollection<HashedFileSystemFileDto>>(files => files.Count == 2 && files.All(file => file.CurrentHash == 42UL)),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIsNotOnSsd_ShouldHashTheFilesSequentially()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, userId: _userId.Value, isContentOnSsd: false)));
|
||||
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")];
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
|
||||
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
|
||||
.Select(file => file with { CurrentHash = 42UL })
|
||||
.ToList()));
|
||||
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockFileHashService.Received(1).HashFilesAsync(
|
||||
Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(),
|
||||
Arg.Is<bool>(shouldParallelizeReads => !shouldParallelizeReads),
|
||||
Arg.Any<Func<Task>>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<bool>(), Arg.Any<bool>(), 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 _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoFilesNeedHashing_ShouldCompleteWithoutHashing()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(0));
|
||||
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
|
||||
await _mockStagingResultsRepository.DidNotReceive().UpdateFileHashesAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCountingFilesFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to count the files to hash"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_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_WhenGettingTheFilesToHashPageFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the files to hash"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUpdatingTheFileHashesFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf"), _hashedFileSystemFileDtoFixture.Create(path: "/books/book2.pdf")];
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(2));
|
||||
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
|
||||
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
|
||||
.Select(file => file with { CurrentHash = 42UL })
|
||||
.ToList()));
|
||||
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to update the file hashes"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockFileHashService.Received(1).HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheHashingCallbackRunsBeforeTheProgressInterval_ShouldNotPublishJobProgressFromTheCallback()
|
||||
{
|
||||
// Arrange
|
||||
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")];
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
|
||||
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(async callInfo =>
|
||||
{
|
||||
await callInfo.Arg<Func<Task>>()();
|
||||
return callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
|
||||
.Select(file => file with { CurrentHash = 42UL })
|
||||
.ToList();
|
||||
});
|
||||
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockStagingResultsRepository.Received(1).UpdateFileHashesAsync(
|
||||
_scanId.Value,
|
||||
Arg.Is<IReadOnlyCollection<HashedFileSystemFileDto>>(files => files.All(file => file.CurrentHash == 42UL)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheHashingCallbackRunsAfterTheProgressInterval_ShouldPublishJobProgressFromTheCallback()
|
||||
{
|
||||
// Arrange
|
||||
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")];
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
|
||||
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
|
||||
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(async callInfo =>
|
||||
{
|
||||
await Task.Delay(150);
|
||||
await callInfo.Arg<Func<Task>>()();
|
||||
return callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
|
||||
.Select(file => file with { CurrentHash = 42UL })
|
||||
.ToList();
|
||||
});
|
||||
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
// The initial progress and the progress published from the hashing callback are both reported.
|
||||
await _mockDomainEventPublisher.Received(2).PublishAsync(Arg.Is<LibraryScanJobProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload()
|
||||
{
|
||||
// Arrange
|
||||
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(0));
|
||||
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
|
||||
|
||||
IMediaLibraryScanJob mockChildJob = Substitute.For<IMediaLibraryScanJob>();
|
||||
mockChildJob.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
_sut.AddChild(mockChildJob);
|
||||
Guid id = Guid.NewGuid();
|
||||
object input = new();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(id, input, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
#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.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanMetadataEnrichmentJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IMediaLibraryScanMetadataEnricher _mockMetadataEnricher;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MediaLibraryScanMetadataEnrichmentJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanMetadataEnrichmentJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanMetadataEnrichmentJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_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);
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanMetadataEnrichmentJob(_mockServiceScopeFactory)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenEnrichmentSucceeds_ShouldPublishProgressChangedEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Music);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _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>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_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);
|
||||
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>());
|
||||
}
|
||||
}
|
||||
+473
@@ -0,0 +1,473 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.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.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;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanProviderConfigurationInvalidationJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanProviderConfigurationInvalidationJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository;
|
||||
private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<MediaLibraryScanProviderConfigurationInvalidationJob> _mockLogger;
|
||||
private readonly MediaLibraryScanProviderConfigurationInvalidationJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanProviderConfigurationInvalidationJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanProviderConfigurationInvalidationJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository);
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
// 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>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_mockLogger = Substitute.For<ILogger<MediaLibraryScanProviderConfigurationInvalidationJob>>();
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanProviderConfigurationInvalidationJob(_mockServiceScopeFactory, _mockLogger)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoFingerprintIsStored_ShouldSeedTheFingerprintsWithoutResettingAnything()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: null);
|
||||
SetupLibraryAndConfigurations(library);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// A missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted.
|
||||
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_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()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE", artworkProvidersConfigurationFingerprint: null);
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job.
|
||||
await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtworkFingerprintDiffers_ShouldResetTheArtworkStatus()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: "STALE");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job.
|
||||
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenFingerprintsMatch_ShouldNotResetAnythingButStillPersistTheFingerprints()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
|
||||
List<LibraryMetadataProviderConfigurationEntity> metadataConfigurations = _libraryMetadataProviderConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1);
|
||||
List<LibraryArtworkProviderConfigurationEntity> artworkConfigurations = _libraryArtworkProviderConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1);
|
||||
SetupLibraryAndConfigurations(library, metadataConfigurations, artworkConfigurations);
|
||||
|
||||
// The stored fingerprints match the ones computed from the current provider configuration.
|
||||
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(metadataConfigurations, false, library.CanDownloadMetadataFromWeb);
|
||||
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, false, library.CanDownloadMetadataFromWeb);
|
||||
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
|
||||
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted.
|
||||
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBothFingerprintsDiffer_ShouldPersistTheUpdatedFingerprintsViaSaveChangesOnly()
|
||||
{
|
||||
// Arrange
|
||||
// Both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity.
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: "STALE_ARTWORK");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// Regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and
|
||||
// flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run.
|
||||
await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the media library"));
|
||||
SetupConfigurations();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_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);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingMetadataConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the metadata provider configurations"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingArtworkConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the artwork provider configurations"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenResettingMetadataStatusFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: null);
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to reset the metadata status"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenResettingArtworkStatusFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: "STALE_ARTWORK");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to reset the artwork status"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenReadingUserSettingsFails_ShouldStillSeedTheFingerprintsAndComplete()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to read the user settings"));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// Reading the user settings is best effort, a failure must not prevent the fingerprints from being persisted.
|
||||
Assert.NotNull(library.MetadataProvidersConfigurationFingerprint);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserSettingsRepositoryIsNotRegistered_ShouldSeedTheFingerprintsAndComplete()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns((IUserSettingsRepository)null!);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The user settings repository is optional, its absence must not prevent the fingerprints from being persisted.
|
||||
Assert.NotNull(library.MetadataProvidersConfigurationFingerprint);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildAndComplete()
|
||||
{
|
||||
// Arrange
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
|
||||
SetupLibraryAndConfigurations(library);
|
||||
|
||||
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
|
||||
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
_sut.AddChild(mockChild);
|
||||
object input = new();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Is<object>(executedInput => executedInput == input), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<LibraryScanFinishedDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the repositories so that the job reads the provided library and its provider configurations.
|
||||
/// </summary>
|
||||
/// <param name="library">The media library the job must read.</param>
|
||||
/// <param name="metadataConfigurations">The metadata provider configurations of the media library.</param>
|
||||
/// <param name="artworkConfigurations">The artwork provider configurations of the media library.</param>
|
||||
private void SetupLibraryAndConfigurations(LibraryEntity library, List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
|
||||
{
|
||||
// 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);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the provider configuration repositories and the user settings repository used by the job.
|
||||
/// </summary>
|
||||
/// <param name="metadataConfigurations">The metadata provider configurations of the media library, if already created by the caller.</param>
|
||||
/// <param name="artworkConfigurations">The artwork provider configurations of the media library, if already created by the caller.</param>
|
||||
private void SetupConfigurations(List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
|
||||
{
|
||||
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>(
|
||||
metadataConfigurations ?? [
|
||||
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1),
|
||||
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2)
|
||||
]));
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(
|
||||
artworkConfigurations ?? [
|
||||
_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1),
|
||||
_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2)
|
||||
]));
|
||||
|
||||
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
}
|
||||
}
|
||||
+464
@@ -0,0 +1,464 @@
|
||||
#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;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanResultsSaveJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanResultsSaveJobTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
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;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly MediaLibraryScanResultsSaveJob _sut;
|
||||
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;
|
||||
private readonly LibraryId _libraryId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanResultsSaveJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanResultsSaveJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_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()));
|
||||
IPathService mockPathService = Substitute.For<IPathService>();
|
||||
mockPathService.GetFileName(Arg.Any<string>()).Returns(callInfo => callInfo.Arg<string>());
|
||||
mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns(callInfo =>
|
||||
{
|
||||
string fileName = callInfo.Arg<string>();
|
||||
int lastDotIndex = fileName.LastIndexOf('.');
|
||||
return lastDotIndex <= 0 ? fileName : fileName[..lastDotIndex];
|
||||
});
|
||||
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanItemMaterializer>))
|
||||
.Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(mockPathTemplateService, mockPathService) });
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_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,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenScanResultsAreApplied_ShouldCreateShellBooksAndPublishFinishedEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["deleted.pdf"]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["changed.pdf"]));
|
||||
_mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePathSet("book1.pdf", "book2.pdf")));
|
||||
_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);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryMediaItemDeletedDomainEvent>(domainEvent => domainEvent.Path == "deleted.pdf"), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Is<IReadOnlyCollection<string>>(paths => paths.Any(path => path == "changed.pdf")), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book1.pdf" && book.Title == "book1" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book2.pdf" && book.Title == "book2" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_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(CreatePathSet()));
|
||||
_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()
|
||||
{
|
||||
// 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(CreatePathSet()));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// No book content changed since the last scan, so the enrichment state of the books must not be reset.
|
||||
await _mockBookRepository.DidNotReceive().ResetEnrichmentStateForPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookAlreadyExists_ShouldSkipInsertingIt()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePathSet("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
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingDeletedPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the deleted paths"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingChangedPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the changed paths"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockSnapshotRepository.DidNotReceive().ApplySnapshotSwapAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApplyingSnapshotSwapFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to apply the snapshot swap"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenResettingEnrichmentStateFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["changed.pdf"]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to reset the enrichment state"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the paths"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingExistingPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePathSet("book1.pdf")));
|
||||
_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);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenInsertingShellBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePathSet("book1.pdf")));
|
||||
_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"));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildWithoutPublishingFinishedEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePathSet()));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
|
||||
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
_sut.AddChild(mockChild);
|
||||
object input = new();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Is<object>(executedInput => executedInput == input), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<LibraryScanFinishedDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookPathYieldsEmptyDerivedTitle_ShouldFallBackToTheFileNameAsTitle()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(CreatePathSet("_.pdf")));
|
||||
_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);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The file name is made only of separators, so the derived title is empty and the raw file name is used as a fallback.
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "_.pdf" && book.Title == "_"), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the set of media library scan snapshot paths that the snapshot repository returns.
|
||||
/// </summary>
|
||||
/// <param name="paths">The paths of the set.</param>
|
||||
/// <returns>The set of paths.</returns>
|
||||
private static IReadOnlySet<string> CreatePathSet(params string[] paths)
|
||||
{
|
||||
return new HashSet<string>(paths, StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ScanFailurePublisher"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScanFailurePublisherTests
|
||||
{
|
||||
private readonly IServiceScopeFactory _mockServiceScopeFactory;
|
||||
private readonly IServiceScope _mockServiceScope;
|
||||
private readonly IServiceProvider _mockServiceProvider;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanFailurePublisherTests"/> class.
|
||||
/// </summary>
|
||||
public ScanFailurePublisherTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PublishAsync_WhenCalled_ShouldPublishLibraryScanFailedDomainEvent()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
Exception exception = new("The scan job failed");
|
||||
|
||||
// Act
|
||||
await ScanFailurePublisher.PublishAsync(_mockServiceScopeFactory, libraryId, compositeId, exception, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(
|
||||
Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId == compositeId
|
||||
&& domainEvent.ErrorMessage.HasValue && domainEvent.ErrorMessage.Value == "The scan job failed"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PublishAsync_WhenPublisherThrows_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => new ValueTask(Task.FromException(new InvalidOperationException("Publishing failed"))));
|
||||
|
||||
// Act
|
||||
Exception? caughtException = null;
|
||||
try
|
||||
{
|
||||
await ScanFailurePublisher.PublishAsync(_mockServiceScopeFactory, libraryId, compositeId, new Exception("boom"), CancellationToken.None);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
caughtException = exception;
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.Null(caughtException);
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
#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.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
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="BooksFileSystemDiscoveryJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BooksFileSystemDiscoveryJobTests
|
||||
{
|
||||
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 IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<BooksFileSystemDiscoveryJob> _mockLogger;
|
||||
private readonly BooksFileSystemDiscoveryJob _sut;
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = 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="BooksFileSystemDiscoveryJobTests"/> class.
|
||||
/// </summary>
|
||||
public BooksFileSystemDiscoveryJobTests()
|
||||
{
|
||||
_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>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_mockLogger = Substitute.For<ILogger<BooksFileSystemDiscoveryJob>>();
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
_sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory, _mockLogger)
|
||||
{
|
||||
ScanId = _scanId,
|
||||
UserId = _userId,
|
||||
LibraryId = _libraryId
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, 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(_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);
|
||||
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_WhenTheLibraryIsOnSsd_ShouldLogThatTheFileSystemReadsRunInParallel()
|
||||
{
|
||||
// Arrange
|
||||
string temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), $"lumina-books-ssd-{Guid.NewGuid()}");
|
||||
Directory.CreateDirectory(temporaryDirectoryPath);
|
||||
File.WriteAllText(Path.Combine(temporaryDirectoryPath, "book.pdf"), "book content");
|
||||
try
|
||||
{
|
||||
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
userId: _userId.Value,
|
||||
libraryType: LibraryType.Book,
|
||||
contentLocations: [temporaryDirectoryPath],
|
||||
isContentOnSsd: true);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(libraryEntity));
|
||||
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Created));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1 && Path.GetFileName(entities.First().Path) == "book.pdf"),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Debug,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(state => state.ToString()!.Contains("solid state drive", StringComparison.Ordinal)),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(temporaryDirectoryPath, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StageFilesInParallelAsync_WhenAFileVanishesBeforeItsMetadataIsRead_ShouldSkipItAndLogAWarning()
|
||||
{
|
||||
// Arrange
|
||||
FileInfo vanishedFile = new(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString(), "vanished.pdf"));
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
|
||||
// Act
|
||||
await _sut.StageFilesInParallelAsync([vanishedFile], stagingBatch, _mockStagingResultsRepository, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(stagingBatch);
|
||||
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(state => state.ToString()!.Contains("vanished.pdf", StringComparison.Ordinal)),
|
||||
Arg.Any<IOException>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StageFilesInParallelAsync_WhenAFileReadThrowsAnUnexpectedException_ShouldRethrowTheRealCause()
|
||||
{
|
||||
// Arrange
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<FileInfo> files = [null!];
|
||||
|
||||
// Act
|
||||
Exception exception = await Assert.ThrowsAsync<NullReferenceException>(() =>
|
||||
_sut.StageFilesInParallelAsync(files, stagingBatch, _mockStagingResultsRepository, CancellationToken.None));
|
||||
|
||||
// Assert
|
||||
// Parallel.For wraps the body exception in an AggregateException, which would otherwise be reported as "One or more errors occurred.".
|
||||
Assert.IsType<NullReferenceException>(exception);
|
||||
}
|
||||
}
|
||||
+482
@@ -0,0 +1,482 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksMediaLibraryScanArtworkEnricher"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BooksMediaLibraryScanArtworkEnricherTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly IArtworkProvider _mockArtworkProvider;
|
||||
private readonly IBookArtworkService _mockBookArtworkService;
|
||||
private readonly IFileHashService _mockFileHashService;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<BooksMediaLibraryScanArtworkEnricher> _mockLogger;
|
||||
private readonly BooksMediaLibraryScanArtworkEnricher _sut;
|
||||
private readonly ServiceProvider _serviceProvider;
|
||||
private readonly Guid _pluginId = Guid.NewGuid();
|
||||
private readonly LibraryId _libraryId;
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanArtworkEnricherTests"/> class.
|
||||
/// </summary>
|
||||
public BooksMediaLibraryScanArtworkEnricherTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockArtworkProviderConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
_mockArtworkProvider = Substitute.For<IArtworkProvider>();
|
||||
_mockArtworkProvider.Name.Returns("Test Provider");
|
||||
_mockArtworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(true);
|
||||
|
||||
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
_mockFileHashService = Substitute.For<IFileHashService>();
|
||||
_mockFileHashService.ComputeFileHash(Arg.Any<string>()).Returns(123UL);
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockLogger = Substitute.For<ILogger<BooksMediaLibraryScanArtworkEnricher>>();
|
||||
|
||||
// The enricher resolves the keyed artwork providers from the scope of the service provider, so a real container is used to honor the keyed registration.
|
||||
ServiceCollection services = new();
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
services.AddSingleton(_mockBookArtworkService);
|
||||
services.AddSingleton(_mockFileHashService);
|
||||
services.AddKeyedSingleton<IArtworkProvider>(_pluginId, _mockArtworkProvider);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
_sut = new BooksMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), _mockLogger);
|
||||
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryType_WhenCalled_ShouldReturnBook()
|
||||
{
|
||||
// Act
|
||||
LibraryType result = _sut.SupportedLibraryType;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryType.Book, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Provider.Error", "Failed to read the configurations"));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloads_ShouldSkipProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(canDownloadMetadataFromWeb: false);
|
||||
SetupConfiguration();
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(true);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloadsButTheProviderIsLocal_ShouldStillResolve()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary(canDownloadMetadataFromWeb: false);
|
||||
SetupConfiguration();
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(false);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtworkProvider.Received(1).GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheBookHasArtwork_ShouldStoreAndPersistEnrichedArtwork()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg", type: ArtworkType.Cover, ordinal: 0)]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(
|
||||
book.LibraryId,
|
||||
book.Id,
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<string>(),
|
||||
book.Title,
|
||||
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkType.Cover, artwork.ArtworkType);
|
||||
Assert.Equal(0, artwork.Ordinal);
|
||||
Assert.Equal(ArtworkStatus.Enriched, artwork.Status);
|
||||
Assert.Equal("Test Provider", artwork.Provider);
|
||||
Assert.Equal("/media/books/cover.jpg", artwork.FileName);
|
||||
Assert.Equal(123UL, artwork.ContentHash);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenAProviderAnswersWithNoArtwork_ShouldMarkTheBookFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
|
||||
Assert.Null(artwork.FileName);
|
||||
Assert.Null(artwork.Provider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheBookFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<IReadOnlyList<ArtworkDto>>(new HttpRequestException("Transient failure.")));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheProviderReturnsRemoteArtworkButDoesNotRequireWebAccess_ShouldMarkTheBookFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheStoredArtworkIsIdentical_ShouldKeepItAndMarkItEnriched()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(false);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
BookArtworkEntity existingArtwork = _bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, contentHash: 123UL, status: ArtworkStatus.Enriched);
|
||||
book.Artwork = [existingArtwork];
|
||||
SetupBooks(book);
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/media/books/local.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Enriched, artwork.Status);
|
||||
Assert.Equal("Test Provider", artwork.Provider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheBookFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
_mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Artwork.Error", "Failed to store the artwork"));
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookArtworkEntity artwork = Assert.Single(book.Artwork);
|
||||
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheBookCountCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to count the books"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheBooksPageCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to read the books"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAuthorsCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to read the authors"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Repository.Error", "Failed to save the changes"));
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
SetupBooks();
|
||||
|
||||
// Act
|
||||
Task Act()
|
||||
{
|
||||
return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the media library reader with a library owned by the test user.
|
||||
/// </summary>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the library allows downloading data from the web.</param>
|
||||
private void SetupLibrary(bool canDownloadMetadataFromWeb = true)
|
||||
{
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Book,
|
||||
canDownloadMetadataFromWeb: canDownloadMetadataFromWeb);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork provider configuration reader with a single enabled configuration for the test plugin.
|
||||
/// </summary>
|
||||
private void SetupConfiguration()
|
||||
{
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, _pluginId, 0)]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the book reader with a single page holding the provided books.
|
||||
/// </summary>
|
||||
/// <param name="books">The books of the page.</param>
|
||||
private void SetupBooks(params BookEntity[] books)
|
||||
{
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(books.Length));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<BookEntity>>(books),
|
||||
Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
Dictionary<Guid, string?> authors = books.ToDictionary(book => book.Id, book => (string?)"Frank Herbert");
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(authors));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork storage so that a book stores its artwork successfully.
|
||||
/// </summary>
|
||||
private void SetupSuccessStore()
|
||||
{
|
||||
_mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/books/cover.jpg"));
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#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('\\');
|
||||
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("track");
|
||||
_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);
|
||||
_mockPathService.GetFileName("C:\\MusicBackup\\track.epub").Returns("track.epub");
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet("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, CreatePathSet("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", '\\');
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MaterializeItemsAsync_WhenPathIsAlreadyUsedByADeletedBook_ShouldNotInsertItAgain()
|
||||
{
|
||||
// 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));
|
||||
_mockBookRepository.GetExistingPathsAsync(_libraryId, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyCollection<string>>(["C:\\Music\\deleted.epub"]));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet("C:\\Music\\deleted.epub"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// A deleted book keeps its stored path, so the scan treats the file as already catalogued and never materializes it again.
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the set of media library scan snapshot paths that the media library scan produces.
|
||||
/// </summary>
|
||||
/// <param name="paths">The paths of the set.</param>
|
||||
/// <returns>The set of paths.</returns>
|
||||
private static IReadOnlySet<string> CreatePathSet(params string[] paths)
|
||||
{
|
||||
return new HashSet<string>(paths, StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
+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 _libraryMetadataProviderConfigurationEntityFixture = 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(
|
||||
[
|
||||
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginAId, rank: 1),
|
||||
_libraryMetadataProviderConfigurationEntityFixture.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);
|
||||
}
|
||||
}
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DebouncedMediaLibraryScanProgressNotifier"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DebouncedMediaLibraryScanProgressNotifierTests
|
||||
{
|
||||
private readonly IHubContext<MediaLibraryScanProgressHub> _mockHubContext;
|
||||
private readonly IHubClients _mockHubClients;
|
||||
private readonly IClientProxy _mockClientProxy;
|
||||
private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker;
|
||||
private readonly DebouncedMediaLibraryScanProgressNotifier _sut;
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly MediaLibraryScanProgressFixture _mediaLibraryScanProgressFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DebouncedMediaLibraryScanProgressNotifierTests"/> class.
|
||||
/// </summary>
|
||||
public DebouncedMediaLibraryScanProgressNotifierTests()
|
||||
{
|
||||
_mockHubContext = Substitute.For<IHubContext<MediaLibraryScanProgressHub>>();
|
||||
_mockHubClients = Substitute.For<IHubClients>();
|
||||
_mockClientProxy = Substitute.For<IClientProxy>();
|
||||
_mockHubContext.Clients.Returns(_mockHubClients);
|
||||
_mockHubClients.Group(Arg.Any<string>()).Returns(_mockClientProxy);
|
||||
_mockClientProxy.SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_mockProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
|
||||
_sut = new DebouncedMediaLibraryScanProgressNotifier(_mockHubContext, _mockProgressTracker);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryProgressUpdateEventAsync_WhenTokenIsCancelled_ShouldNotPublishOrQueryProgress()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
_mockProgressTracker.DidNotReceive().GetScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryProgressUpdateEventAsync_WhenProgressExists_ShouldSendProgressUpdateToGroup()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: compositeId.ScanId,
|
||||
userId: compositeId.UserId,
|
||||
completedJobs: 1,
|
||||
totalJobs: 2,
|
||||
status: LibraryScanJobStatus.Running);
|
||||
_mockProgressTracker.GetScanProgress(compositeId).Returns(Result.From(progress));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_mockHubClients.Received(1).Group(compositeId.ToString());
|
||||
await _mockClientProxy.Received(1).SendCoreAsync(
|
||||
"libraryScanProgressUpdateEvent",
|
||||
Arg.Is<object?[]>(args => args.Length == 1
|
||||
&& args[0] != null
|
||||
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Running.ToString()),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryProgressUpdateEventAsync_WhenProgressIsMissing_ShouldNotSendUpdate()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_mockProgressTracker.GetScanProgress(compositeId)
|
||||
.Returns(Error.Failure("Tracking.Error", "The scan progress is missing"));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanFinishedEventAsync_WhenProgressExists_ShouldSendFinishedEventWithCompletedStatus()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: compositeId.ScanId,
|
||||
userId: compositeId.UserId,
|
||||
completedJobs: 1,
|
||||
totalJobs: 2,
|
||||
status: LibraryScanJobStatus.Running);
|
||||
_mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.Received(1).SendCoreAsync(
|
||||
"libraryScanFinishedEvent",
|
||||
Arg.Is<object?[]>(args => args.Length == 1
|
||||
&& args[0] != null
|
||||
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Completed.ToString()),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanFinishedEventAsync_WhenProgressIsMissing_ShouldNotSendFinishedEvent()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_mockProgressTracker.RemoveScanProgress(compositeId)
|
||||
.Returns(Error.Failure("Tracking.Error", "The scan progress is missing"));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanFailedEventAsync_WhenProgressExists_ShouldSendFailedEventWithFailedStatus()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: compositeId.ScanId,
|
||||
userId: compositeId.UserId,
|
||||
completedJobs: 1,
|
||||
totalJobs: 2,
|
||||
status: LibraryScanJobStatus.Running);
|
||||
_mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanFailedEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.Received(1).SendCoreAsync(
|
||||
"libraryScanFailedEvent",
|
||||
Arg.Is<object?[]>(args => args.Length == 1
|
||||
&& args[0] != null
|
||||
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Failed.ToString()),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanFinishedEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanFinishedEventAsync(compositeId, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
_mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanFailedEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanFailedEventAsync(compositeId, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
_mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanCancelledEventAsync_WhenProgressExists_ShouldSendCancelledEventWithCanceledStatus()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: compositeId.ScanId,
|
||||
userId: compositeId.UserId,
|
||||
completedJobs: 1,
|
||||
totalJobs: 2,
|
||||
status: LibraryScanJobStatus.Pending);
|
||||
_mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanCancelledEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.Received(1).SendCoreAsync(
|
||||
"libraryScanCancelledEvent",
|
||||
Arg.Is<object?[]>(args => args.Length == 1
|
||||
&& args[0] != null
|
||||
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Canceled.ToString()),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanCancelledEventAsync_WhenProgressIsMissing_ShouldNotSendCancelledEvent()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
_mockProgressTracker.RemoveScanProgress(compositeId)
|
||||
.Returns(Error.Failure("Tracking.Error", "The scan progress is missing"));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanCancelledEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanCancelledEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryScanCancelledEventAsync(compositeId, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
_mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
|
||||
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLibraryScanFinishedEventAsync_WhenADebouncedUpdateWasScheduledForTheScan_ShouldRemoveTheDebouncer()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
// The scheduled update is registered by the progress update even when the progress is missing, which also avoids sending an update event.
|
||||
_mockProgressTracker.GetScanProgress(compositeId)
|
||||
.Returns(Error.Failure("Tracking.Error", "The scan progress is missing"));
|
||||
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
|
||||
scanId: compositeId.ScanId,
|
||||
userId: compositeId.UserId,
|
||||
completedJobs: 1,
|
||||
totalJobs: 2,
|
||||
status: LibraryScanJobStatus.Running);
|
||||
_mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress));
|
||||
|
||||
// Act
|
||||
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None);
|
||||
await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockClientProxy.Received(1).SendCoreAsync(
|
||||
"libraryScanFinishedEvent",
|
||||
Arg.Is<object?[]>(args => args.Length == 1
|
||||
&& args[0] != null
|
||||
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Completed.ToString()),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanProgressHub"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanProgressHubTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task SubscribeToScan_WhenCalled_ShouldAddTheConnectionToTheGroupOfTheAuthenticatedUser()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanProgressHub sut = new();
|
||||
HubCallerContext context = Substitute.For<HubCallerContext>();
|
||||
context.ConnectionId.Returns("connection-1");
|
||||
IGroupManager groupManager = Substitute.For<IGroupManager>();
|
||||
sut.Context = context;
|
||||
sut.Groups = groupManager;
|
||||
Guid scanId = Guid.NewGuid();
|
||||
Guid userId = Guid.NewGuid();
|
||||
// The user is always taken from the authenticated connection, never from the client.
|
||||
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())]));
|
||||
context.User.Returns(user);
|
||||
|
||||
// Act
|
||||
await sut.SubscribeToScan(scanId);
|
||||
|
||||
// Assert
|
||||
await groupManager.Received(1).AddToGroupAsync("connection-1", $"{scanId}-{userId}", CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeToScan_WhenUserClaimIsMissing_ShouldNotAddTheConnectionToAnyGroup()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanProgressHub sut = new();
|
||||
HubCallerContext context = Substitute.For<HubCallerContext>();
|
||||
context.ConnectionId.Returns("connection-1");
|
||||
IGroupManager groupManager = Substitute.For<IGroupManager>();
|
||||
sut.Context = context;
|
||||
sut.Groups = groupManager;
|
||||
Guid scanId = Guid.NewGuid();
|
||||
ClaimsPrincipal user = new(new ClaimsIdentity());
|
||||
context.User.Returns(user);
|
||||
|
||||
// Act
|
||||
await sut.SubscribeToScan(scanId);
|
||||
|
||||
// Assert
|
||||
await groupManager.DidNotReceive().AddToGroupAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeToScan_WhenUserIdClaimIsNotAGuid_ShouldNotAddTheConnectionToAnyGroup()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanProgressHub sut = new();
|
||||
HubCallerContext context = Substitute.For<HubCallerContext>();
|
||||
context.ConnectionId.Returns("connection-1");
|
||||
IGroupManager groupManager = Substitute.For<IGroupManager>();
|
||||
sut.Context = context;
|
||||
sut.Groups = groupManager;
|
||||
Guid scanId = Guid.NewGuid();
|
||||
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "not-a-guid")]));
|
||||
context.User.Returns(user);
|
||||
|
||||
// Act
|
||||
await sut.SubscribeToScan(scanId);
|
||||
|
||||
// Assert
|
||||
await groupManager.DidNotReceive().AddToGroupAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibrariesScanQueue"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibrariesScanQueueTests
|
||||
{
|
||||
private readonly MediaLibrariesScanQueue _sut = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task Writer_WhenScanIsWritten_ShouldAllowReadingItFromReader()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId scanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
bool writeResult = _sut.Writer.TryWrite(scanId);
|
||||
MediaLibraryScanCompositeId readScanId = await _sut.Reader.ReadAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(writeResult);
|
||||
Assert.Equal(scanId, readScanId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Writer_WhenMultipleScansAreWritten_ShouldReadThemInFifoOrder()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId firstScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanCompositeId secondScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanCompositeId thirdScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
_sut.Writer.TryWrite(firstScanId);
|
||||
_sut.Writer.TryWrite(secondScanId);
|
||||
_sut.Writer.TryWrite(thirdScanId);
|
||||
MediaLibraryScanCompositeId firstReadScanId = await _sut.Reader.ReadAsync(CancellationToken.None);
|
||||
MediaLibraryScanCompositeId secondReadScanId = await _sut.Reader.ReadAsync(CancellationToken.None);
|
||||
MediaLibraryScanCompositeId thirdReadScanId = await _sut.Reader.ReadAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// The scan processor relies on the queue order: scans must run in the order in which they were queued.
|
||||
Assert.Equal(firstScanId, firstReadScanId);
|
||||
Assert.Equal(secondScanId, secondReadScanId);
|
||||
Assert.Equal(thirdScanId, thirdReadScanId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reader_WhenQueueIsEmpty_ShouldNotCompleteUntilAScanIsWritten()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId scanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
|
||||
// Act
|
||||
Task<MediaLibraryScanCompositeId> readTask = _sut.Reader.ReadAsync(CancellationToken.None).AsTask();
|
||||
_sut.Writer.TryWrite(scanId);
|
||||
|
||||
// Assert
|
||||
MediaLibraryScanCompositeId readScanId = await readTask;
|
||||
Assert.Equal(scanId, readScanId);
|
||||
}
|
||||
}
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
#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.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanProcessorJob"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaLibraryScanProcessorJobTests : IDisposable
|
||||
{
|
||||
private static readonly TimeSpan s_testTimeout = TimeSpan.FromSeconds(5);
|
||||
private readonly MediaLibrariesScanQueue _queue;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryScanRepository _mockLibraryScanRepository;
|
||||
private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService;
|
||||
private readonly IDomainEventPublisher _mockDomainEventPublisher;
|
||||
private readonly ILogger<MediaLibraryScanProcessorJob> _mockLogger;
|
||||
private readonly ServiceProvider _serviceProvider;
|
||||
private readonly MediaLibraryScanProcessorJob _sut;
|
||||
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
|
||||
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
|
||||
private readonly MediaLibraryScanDiscoveryJobFixture _mediaLibraryScanDiscoveryJobFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanProcessorJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanProcessorJobTests()
|
||||
{
|
||||
_queue = new MediaLibrariesScanQueue();
|
||||
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
|
||||
_mockCancellationTracker.GetTokenForScan(Arg.Any<MediaLibraryScanCompositeId>()).Returns(CancellationToken.None);
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryScanRepository = Substitute.For<ILibraryScanRepository>();
|
||||
_mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository);
|
||||
_mockMediaLibraryScanningService = Substitute.For<IMediaLibraryScanningService>();
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockLogger = Substitute.For<ILogger<MediaLibraryScanProcessorJob>>();
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockMediaLibraryScanningService);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
_sut = new MediaLibraryScanProcessorJob(
|
||||
_queue,
|
||||
_mockCancellationTracker,
|
||||
_serviceProvider.GetRequiredService<IServiceScopeFactory>(),
|
||||
_mockLogger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenScansAreQueued_ShouldProcessThemOneAtATimeInOrder()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId firstScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanCompositeId secondScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
RegisterScan(firstScanId, LibraryScanJobStatus.Pending);
|
||||
RegisterScan(secondScanId, LibraryScanJobStatus.Pending);
|
||||
TaskCompletionSource<bool> releaseFirstScan = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
// ExecutionStarted is signaled before the callback runs, and resumes the test on another thread, so the test waits for the callback itself to record the scan.
|
||||
TaskCompletionSource firstScanRecorded = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
List<Guid> startedScanIds = [];
|
||||
FakeMediaLibraryScanDiscoveryJob firstRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: async _ =>
|
||||
{
|
||||
startedScanIds.Add(firstScanId.ScanId.Value);
|
||||
firstScanRecorded.SetResult();
|
||||
await releaseFirstScan.Task;
|
||||
});
|
||||
FakeMediaLibraryScanDiscoveryJob secondRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: _ =>
|
||||
{
|
||||
startedScanIds.Add(secondScanId.ScanId.Value);
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
RegisterRootJob(firstScanId, firstRootJob);
|
||||
RegisterRootJob(secondScanId, secondRootJob);
|
||||
await _sut.StartAsync(CancellationToken.None);
|
||||
|
||||
// Act
|
||||
_queue.Writer.TryWrite(firstScanId);
|
||||
_queue.Writer.TryWrite(secondScanId);
|
||||
await firstScanRecorded.Task.WaitAsync(s_testTimeout);
|
||||
|
||||
// Assert
|
||||
// The second scan must not start while the job graph of the first one is still executing.
|
||||
Assert.Equal([firstScanId.ScanId.Value], startedScanIds);
|
||||
Assert.Equal(0, secondRootJob.ExecutionCount);
|
||||
|
||||
releaseFirstScan.SetResult(true);
|
||||
await secondRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
|
||||
Assert.Equal([firstScanId.ScanId.Value, secondScanId.ScanId.Value], startedScanIds);
|
||||
Assert.Equal(1, firstRootJob.ExecutionCount);
|
||||
await _sut.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenScanIsNotPending_ShouldSkipItAndProcessTheNextScan()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId completedScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
RegisterScan(completedScanId, LibraryScanJobStatus.Completed);
|
||||
RegisterScan(pendingScanId, LibraryScanJobStatus.Pending);
|
||||
FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
|
||||
RegisterRootJob(pendingScanId, pendingRootJob);
|
||||
await _sut.StartAsync(CancellationToken.None);
|
||||
|
||||
// Act
|
||||
_queue.Writer.TryWrite(completedScanId);
|
||||
_queue.Writer.TryWrite(pendingScanId);
|
||||
await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
|
||||
|
||||
// Assert
|
||||
// A scan that was cancelled or otherwise finished while it was waiting for its turn must not be started.
|
||||
await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == completedScanId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMediaLibraryScanningService.Received(1).StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == pendingScanId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
await _sut.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenScanTokenIsAlreadyCancelled_ShouldSkipItAndProcessTheNextScan()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId cancelledScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
RegisterScan(cancelledScanId, LibraryScanJobStatus.Pending);
|
||||
RegisterScan(pendingScanId, LibraryScanJobStatus.Pending);
|
||||
using CancellationTokenSource cancelledTokenSource = new();
|
||||
cancelledTokenSource.Cancel();
|
||||
_mockCancellationTracker.GetTokenForScan(cancelledScanId).Returns(cancelledTokenSource.Token);
|
||||
FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
|
||||
RegisterRootJob(pendingScanId, pendingRootJob);
|
||||
await _sut.StartAsync(CancellationToken.None);
|
||||
|
||||
// Act
|
||||
_queue.Writer.TryWrite(cancelledScanId);
|
||||
_queue.Writer.TryWrite(pendingScanId);
|
||||
await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
|
||||
|
||||
// Assert
|
||||
// A scan that was cancelled while it was waiting for its turn is not even loaded from the repository.
|
||||
await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(
|
||||
cancelledScanId.ScanId.Value,
|
||||
Arg.Any<bool>(),
|
||||
false,
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == cancelledScanId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMediaLibraryScanningService.Received(1).StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == pendingScanId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _sut.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPreparingAScanFails_ShouldReportTheFailureForThatScanAndProcessTheNextScan()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId failingScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
RegisterScan(failingScanId, LibraryScanJobStatus.Pending);
|
||||
RegisterScan(pendingScanId, LibraryScanJobStatus.Pending);
|
||||
Error error = Error.Failure(description: "Failed to prepare the media library scan");
|
||||
_mockMediaLibraryScanningService.StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == failingScanId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
|
||||
RegisterRootJob(pendingScanId, pendingRootJob);
|
||||
await _sut.StartAsync(CancellationToken.None);
|
||||
|
||||
// Act
|
||||
_queue.Writer.TryWrite(failingScanId);
|
||||
_queue.Writer.TryWrite(pendingScanId);
|
||||
await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
|
||||
|
||||
// Assert
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(
|
||||
Arg.Is<IDomainEvent>(domainEvent => domainEvent.GetType() == typeof(LibraryScanFailedDomainEvent)
|
||||
&& ((LibraryScanFailedDomainEvent)domainEvent).MediaLibraryScanCompositeId == failingScanId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(1, pendingRootJob.ExecutionCount);
|
||||
await _sut.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenExecutingAScanIsCancelled_ShouldNotStopProcessingTheNextScan()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId cancelledScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
RegisterScan(cancelledScanId, LibraryScanJobStatus.Pending);
|
||||
RegisterScan(pendingScanId, LibraryScanJobStatus.Pending);
|
||||
FakeMediaLibraryScanDiscoveryJob cancelledRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(
|
||||
onExecute: _ => throw new OperationCanceledException());
|
||||
FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
|
||||
RegisterRootJob(cancelledScanId, cancelledRootJob);
|
||||
RegisterRootJob(pendingScanId, pendingRootJob);
|
||||
await _sut.StartAsync(CancellationToken.None);
|
||||
|
||||
// Act
|
||||
_queue.Writer.TryWrite(cancelledScanId);
|
||||
_queue.Writer.TryWrite(pendingScanId);
|
||||
await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(1, cancelledRootJob.ExecutionCount);
|
||||
Assert.Equal(1, pendingRootJob.ExecutionCount);
|
||||
// A cancelled scan was already reported by its own cancellation event, so no failure is published for it.
|
||||
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
|
||||
await _sut.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenExecutingAScanFails_ShouldReportTheFailureForThatScanAndProcessTheNextScan()
|
||||
{
|
||||
// Arrange
|
||||
MediaLibraryScanCompositeId failingScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create();
|
||||
RegisterScan(failingScanId, LibraryScanJobStatus.Pending);
|
||||
RegisterScan(pendingScanId, LibraryScanJobStatus.Pending);
|
||||
FakeMediaLibraryScanDiscoveryJob failingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(
|
||||
onExecute: _ => throw new InvalidOperationException("The scan job payload failed"));
|
||||
FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
|
||||
RegisterRootJob(failingScanId, failingRootJob);
|
||||
RegisterRootJob(pendingScanId, pendingRootJob);
|
||||
await _sut.StartAsync(CancellationToken.None);
|
||||
|
||||
// Act
|
||||
_queue.Writer.TryWrite(failingScanId);
|
||||
_queue.Writer.TryWrite(pendingScanId);
|
||||
await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
|
||||
|
||||
// Assert
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(
|
||||
Arg.Is<IDomainEvent>(domainEvent => domainEvent.GetType() == typeof(LibraryScanFailedDomainEvent)
|
||||
&& ((LibraryScanFailedDomainEvent)domainEvent).MediaLibraryScanCompositeId == failingScanId),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(1, pendingRootJob.ExecutionCount);
|
||||
await _sut.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a media library scan with the given status in the mocked repository.
|
||||
/// </summary>
|
||||
/// <param name="compositeId">The composite identifier of the scan to register.</param>
|
||||
/// <param name="status">The status of the media library scan.</param>
|
||||
/// <returns>The created media library scan entity.</returns>
|
||||
private LibraryScanEntity RegisterScan(MediaLibraryScanCompositeId compositeId, LibraryScanJobStatus status)
|
||||
{
|
||||
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
|
||||
id: compositeId.ScanId.Value,
|
||||
userId: compositeId.UserId.Value,
|
||||
status: status);
|
||||
_mockLibraryScanRepository
|
||||
.GetByIdAsync(scan.Id, Arg.Any<bool>(), false, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryScanEntity?>(scan));
|
||||
return scan;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the file system discovery job that the mocked scanning service prepares for a media library scan.
|
||||
/// </summary>
|
||||
/// <param name="compositeId">The composite identifier of the scan that owns the job.</param>
|
||||
/// <param name="rootJob">The root job to return when the scan is prepared.</param>
|
||||
private void RegisterRootJob(MediaLibraryScanCompositeId compositeId, IMediaLibraryScanDiscoveryJob rootJob)
|
||||
{
|
||||
_mockMediaLibraryScanningService.StartScanAsync(
|
||||
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == compositeId.ScanId.Value),
|
||||
Arg.Any<LibraryType>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(rootJob));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the test dependencies.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_serviceProvider.Dispose();
|
||||
}
|
||||
}
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookArtworkService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookArtworkServiceTests
|
||||
{
|
||||
private readonly IEnvironmentContext _mockEnvironmentContext;
|
||||
private readonly IFileTypeService _mockFileTypeService;
|
||||
private readonly IFileProviderService _mockFileProviderService;
|
||||
private readonly IDirectoryProviderService _mockDirectoryProviderService;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly IHttpClientFactory _mockHttpClientFactory;
|
||||
private readonly IOptions<MediaSettingsDto> _mockMediaSettingsOptions;
|
||||
private readonly BookArtworkService _sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly PathSegmentFixture _pathSegmentFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookArtworkServiceTests"/> class.
|
||||
/// </summary>
|
||||
public BookArtworkServiceTests()
|
||||
{
|
||||
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
|
||||
_mockFileTypeService = Substitute.For<IFileTypeService>();
|
||||
_mockFileProviderService = Substitute.For<IFileProviderService>();
|
||||
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
|
||||
_mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
|
||||
_mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
|
||||
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
|
||||
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
|
||||
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
|
||||
|
||||
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books");
|
||||
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
|
||||
_mockMediaSettingsOptions.Value.Returns(mediaSettings);
|
||||
|
||||
_sut = new BookArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("FileSystem.Error", result.FirstError.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteBookArtwork_WhenListingTheCoverFilesFails_ShouldReturnSuccessAndDeleteNothing()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string authorName = "Test Author";
|
||||
string bookTitle = "Test Book";
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files"));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteBookArtwork_WhenCalled_ShouldDeleteTheCoverFilesInTheBookDirectory()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string authorName = "Test Author";
|
||||
string bookTitle = "Test Book";
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
|
||||
FileSystemPathId otherFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "metadata.json"));
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, otherFileId]));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(otherFileId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteBookArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteBookArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any<FileSystemPathId>(), true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path and file system services so that the artwork is stored into the given directory.
|
||||
/// </summary>
|
||||
/// <param name="artworkDirectoryPath">The file system path of the directory into which the artwork is stored.</param>
|
||||
private void MockArtworkDirectoryStubs(string artworkDirectoryPath)
|
||||
{
|
||||
string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media");
|
||||
string booksPath = Path.Combine(mediaRoot, "books");
|
||||
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot));
|
||||
_mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath));
|
||||
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
string name = callInfo.Arg<string>();
|
||||
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
|
||||
});
|
||||
|
||||
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
string name = callInfo.ArgAt<string>(0);
|
||||
string identifier = callInfo.ArgAt<string>(1);
|
||||
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
|
||||
});
|
||||
|
||||
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
|
||||
|
||||
// Every directory except the artwork directory itself already exists, so that only the final directory is created.
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>()))));
|
||||
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory that the artwork of the book is stored into.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="bookId">The Id of the book.</param>
|
||||
/// <param name="libraryName">The name of the media library the book belongs to.</param>
|
||||
/// <param name="authorName">The name of the author of the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <returns>The expected file system path of the book artwork directory.</returns>
|
||||
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle)
|
||||
{
|
||||
return Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"media",
|
||||
"books",
|
||||
$"{libraryName}-{libraryId}",
|
||||
authorName,
|
||||
$"{bookTitle}-{bookId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenUploadedStreamIsNull_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", null!, "cover.jpg", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenUploadedStreamIsEmpty_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream emptyStream = new([]);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", emptyStream, "cover.jpg", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenUploadedStreamExceedsTheMaximumSize_ShouldReturnFileTooLarge()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream oversizedStream = new(new byte[(10 * 1024 * 1024) + 1]);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", oversizedStream, "cover.jpg", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
|
||||
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
|
||||
+583
@@ -0,0 +1,583 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MetadataAggregator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MetadataAggregatorTests
|
||||
{
|
||||
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
|
||||
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
|
||||
private readonly IsbnDtoFixture _isbnDtoFixture = new();
|
||||
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
|
||||
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
|
||||
private readonly GenreDtoFixture _genreDtoFixture = new();
|
||||
private readonly TagDtoFixture _tagDtoFixture = new();
|
||||
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothMetadataHaveScalarValues_ShouldKeepTheFirstValues()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
title: "First Title",
|
||||
originalTitle: "First Original Title",
|
||||
description: "First Description",
|
||||
publisher: "First Publisher",
|
||||
pageCount: 100,
|
||||
format: BookFormat.Hardcover,
|
||||
edition: "First Edition",
|
||||
volumeNumber: 1,
|
||||
asin: "FIRST-ASIN",
|
||||
goodreadsId: "FIRST-GOODREADS",
|
||||
lccn: "FIRST-LCCN",
|
||||
oclcNumber: "FIRST-OCLC",
|
||||
openLibraryId: "FIRST-OL",
|
||||
libraryThingId: "FIRST-LT",
|
||||
googleBooksId: "FIRST-GOOGLE",
|
||||
barnesAndNobleId: "FIRST-BN",
|
||||
appleBooksId: "FIRST-APPLE",
|
||||
coverImagePath: "First Cover");
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
title: "Second Title",
|
||||
originalTitle: "Second Original Title",
|
||||
description: "Second Description",
|
||||
publisher: "Second Publisher",
|
||||
pageCount: 200,
|
||||
format: BookFormat.Paperback,
|
||||
edition: "Second Edition",
|
||||
volumeNumber: 2,
|
||||
asin: "SECOND-ASIN",
|
||||
goodreadsId: "SECOND-GOODREADS",
|
||||
lccn: "SECOND-LCCN",
|
||||
oclcNumber: "SECOND-OCLC",
|
||||
openLibraryId: "SECOND-OL",
|
||||
libraryThingId: "SECOND-LT",
|
||||
googleBooksId: "SECOND-GOOGLE",
|
||||
barnesAndNobleId: "SECOND-BN",
|
||||
appleBooksId: "SECOND-APPLE",
|
||||
coverImagePath: "First Cover");
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("First Title", result.Title);
|
||||
Assert.Equal("First Original Title", result.OriginalTitle);
|
||||
Assert.Equal("First Description", result.Description);
|
||||
Assert.Equal("First Publisher", result.Publisher);
|
||||
Assert.Equal(100, result.PageCount);
|
||||
Assert.Equal(BookFormat.Hardcover, result.Format);
|
||||
Assert.Equal("First Edition", result.Edition);
|
||||
Assert.Equal(1, result.VolumeNumber);
|
||||
Assert.Equal("FIRST-ASIN", result.ASIN);
|
||||
Assert.Equal("FIRST-GOODREADS", result.GoodreadsId);
|
||||
Assert.Equal("FIRST-LCCN", result.LCCN);
|
||||
Assert.Equal("FIRST-OCLC", result.OCLCNumber);
|
||||
Assert.Equal("FIRST-OL", result.OpenLibraryId);
|
||||
Assert.Equal("FIRST-LT", result.LibraryThingId);
|
||||
Assert.Equal("FIRST-GOOGLE", result.GoogleBooksId);
|
||||
Assert.Equal("FIRST-BN", result.BarnesAndNobleId);
|
||||
Assert.Equal("FIRST-APPLE", result.AppleBooksId);
|
||||
Assert.Equal("First Cover", result.CoverImagePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenFirstHasNullScalars_ShouldFallBackToTheSecondValues()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeTitle: false,
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: null,
|
||||
description: null,
|
||||
publisher: null,
|
||||
pageCount: null);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Second Title",
|
||||
description: "Second Description",
|
||||
publisher: "Second Publisher",
|
||||
pageCount: 200);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Second Title", result.Title);
|
||||
Assert.Equal("Second Description", result.Description);
|
||||
Assert.Equal("Second Publisher", result.Publisher);
|
||||
Assert.Equal(200, result.PageCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveNullScalars_ShouldReturnNullScalars()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeTitle: false,
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: null,
|
||||
coverImagePath: null);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeTitle: false,
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: null,
|
||||
coverImagePath: null);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Title);
|
||||
Assert.Null(result.Description);
|
||||
Assert.Null(result.Publisher);
|
||||
Assert.Null(result.PageCount);
|
||||
Assert.Null(result.Format);
|
||||
Assert.Null(result.Edition);
|
||||
Assert.Null(result.VolumeNumber);
|
||||
Assert.Null(result.Series);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveReleaseInfo_ShouldCoalesceEachField()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, releaseCountry: ReleaseCountry.US));
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2010, 5, 5), reReleaseYear: 2010, releaseCountry: ReleaseCountry.GB, releaseVersion: "2.0"));
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate);
|
||||
Assert.Equal(2001, result.ReleaseInfo.OriginalReleaseYear);
|
||||
Assert.Equal(new DateOnly(2010, 5, 5), result.ReleaseInfo.ReReleaseDate);
|
||||
Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear);
|
||||
Assert.Equal(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry);
|
||||
Assert.Equal("2.0", result.ReleaseInfo.ReleaseVersion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenFirstReleaseInfoIsNull_ShouldUseTheSecondReleaseInfo()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover");
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001));
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothReleaseInfosAreNull_ShouldReturnNullReleaseInfo()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover");
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover");
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ReleaseInfo);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveGenres_ShouldUnionAndDeDuplicateByName()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
genres: [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Space opera")]);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
genres: [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Fantasy")]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, result.Genres!.Count);
|
||||
Assert.Contains(result.Genres, genre => genre.Name == "Science fiction");
|
||||
Assert.Contains(result.Genres, genre => genre.Name == "Space opera");
|
||||
Assert.Contains(result.Genres, genre => genre.Name == "Fantasy");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveTags_ShouldUnionAndDeDuplicateByName()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
tags: [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag B")]);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
tags: [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag C")]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, result.Tags!.Count);
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "Tag A");
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "Tag B");
|
||||
Assert.Contains(result.Tags, tag => tag.Name == "Tag C");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveIsbns_ShouldUnionAndDeDuplicateByValue()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
isbns: [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)]);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
isbns: [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13), _isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Isbns!.Count);
|
||||
Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157");
|
||||
Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveContributors_ShouldUnionAndDeDuplicateByDisplayNameAndRole()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
contributors: [_mediaContributorDtoFixture.Create("Author A", MediaContributorRole.Author)]);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
contributors: [_mediaContributorDtoFixture.Create("Author A", MediaContributorRole.Author), _mediaContributorDtoFixture.Create("Translator B", MediaContributorRole.Translator)]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Contributors!.Count);
|
||||
Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Author A");
|
||||
Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Translator B");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveRatings_ShouldUnionAndDeDuplicateBySource()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
ratings: [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)]);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
ratings: [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null), _bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Ratings!.Count);
|
||||
Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.Calibre);
|
||||
Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.OpenLibrary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenOnlyFirstHasCollections_ShouldReturnTheFirstCollections()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
tags: [_tagDtoFixture.Create(name: "Tag A")],
|
||||
genres: [_genreDtoFixture.Create(name: "Genre A")],
|
||||
isbns: [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)],
|
||||
contributors: [_mediaContributorDtoFixture.Create("Author A", MediaContributorRole.Author)],
|
||||
ratings: [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)]);
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover");
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Tag A", Assert.Single(result.Tags!).Name);
|
||||
Assert.Equal("Genre A", Assert.Single(result.Genres!).Name);
|
||||
Assert.Equal("9780306406157", Assert.Single(result.Isbns!).Value);
|
||||
Assert.Equal("Author A", Assert.Single(result.Contributors!).Name!.DisplayName);
|
||||
Assert.Equal(BookRatingSource.Calibre, Assert.Single(result.Ratings!).Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenOnlySecondHasCollections_ShouldReturnTheSecondCollections()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover");
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
tags: [_tagDtoFixture.Create(name: "Tag B")],
|
||||
genres: [_genreDtoFixture.Create(name: "Genre B")],
|
||||
isbns: [_isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)],
|
||||
contributors: [_mediaContributorDtoFixture.Create("Author B", MediaContributorRole.Author)],
|
||||
ratings: [_bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Tag B", Assert.Single(result.Tags!).Name);
|
||||
Assert.Equal("Genre B", Assert.Single(result.Genres!).Name);
|
||||
Assert.Equal("0306406152", Assert.Single(result.Isbns!).Value);
|
||||
Assert.Equal("Author B", Assert.Single(result.Contributors!).Name!.DisplayName);
|
||||
Assert.Equal(BookRatingSource.OpenLibrary, Assert.Single(result.Ratings!).Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveNullCollections_ShouldReturnNullCollections()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover");
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeLanguage: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover");
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Genres);
|
||||
Assert.Null(result.Tags);
|
||||
Assert.Null(result.Isbns);
|
||||
Assert.Null(result.Contributors);
|
||||
Assert.Null(result.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Merge_WhenBothHaveLanguages_ShouldKeepTheFirstLanguage()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataDto first = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
language: _languageInfoDtoFixture.Create(languageCode: "en", languageName: "English", nativeName: "English"));
|
||||
BookMetadataDto second = _bookMetadataDtoFixture.Create(
|
||||
includeReleaseInfo: false,
|
||||
includeGenres: false,
|
||||
includeTags: false,
|
||||
includeFormat: false,
|
||||
includeVolumeNumber: false,
|
||||
title: "Title",
|
||||
coverImagePath: "First Cover",
|
||||
language: _languageInfoDtoFixture.Create(languageCode: "de", languageName: "German", nativeName: "Deutsch"));
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = MetadataAggregator.Merge(first, second);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("en", result.Language!.LanguageCode);
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookReaderEnablementCache"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookReaderEnablementCacheTests
|
||||
{
|
||||
private readonly BookReaderEnablementCache _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void Get_WhenNothingIsCached_ShouldReturnNull()
|
||||
{
|
||||
// Act
|
||||
bool? result = _sut.Get(Guid.NewGuid(), Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)] // Reader enabled.
|
||||
[InlineData(false)] // Reader disabled.
|
||||
public void Set_WhenCalled_ThenGetShouldReturnTheCachedValue(bool isEnabled)
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
_sut.Set(libraryId, pluginId, isEnabled);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(isEnabled, _sut.Get(libraryId, pluginId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Invalidate_WhenCalled_ShouldRemoveOnlyTheGivenLibraryAndPluginPair()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid secondPluginId = Guid.NewGuid();
|
||||
_sut.Set(libraryId, firstPluginId, isEnabled: true);
|
||||
_sut.Set(libraryId, secondPluginId, isEnabled: false);
|
||||
|
||||
// Act
|
||||
_sut.Invalidate(libraryId, firstPluginId);
|
||||
|
||||
// Assert
|
||||
Assert.Null(_sut.Get(libraryId, firstPluginId));
|
||||
Assert.False(_sut.Get(libraryId, secondPluginId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidateLibrary_WhenCalled_ShouldRemoveEveryEntryOfTheLibraryAndKeepTheOthers()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid otherLibraryId = Guid.NewGuid();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
Guid otherPluginId = Guid.NewGuid();
|
||||
_sut.Set(libraryId, pluginId, isEnabled: true);
|
||||
_sut.Set(libraryId, otherPluginId, isEnabled: false);
|
||||
_sut.Set(otherLibraryId, pluginId, isEnabled: true);
|
||||
|
||||
// Act
|
||||
_sut.InvalidateLibrary(libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.Null(_sut.Get(libraryId, pluginId));
|
||||
Assert.Null(_sut.Get(libraryId, otherPluginId));
|
||||
Assert.True(_sut.Get(otherLibraryId, pluginId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidatePlugin_WhenCalled_ShouldRemoveEveryEntryOfThePluginAndKeepTheOthers()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid otherLibraryId = Guid.NewGuid();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
Guid otherPluginId = Guid.NewGuid();
|
||||
_sut.Set(libraryId, pluginId, isEnabled: true);
|
||||
_sut.Set(otherLibraryId, pluginId, isEnabled: false);
|
||||
_sut.Set(libraryId, otherPluginId, isEnabled: true);
|
||||
|
||||
// Act
|
||||
_sut.InvalidatePlugin(pluginId);
|
||||
|
||||
// Assert
|
||||
Assert.Null(_sut.Get(libraryId, pluginId));
|
||||
Assert.Null(_sut.Get(otherLibraryId, pluginId));
|
||||
Assert.True(_sut.Get(libraryId, otherPluginId));
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
||||
using Lumina.Application.Common.Infrastructure.Reading;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Lumina.Plugins.Contracts.Core.Reading;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookReaderRegistry"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookReaderRegistryTests
|
||||
{
|
||||
private readonly IPluginManager _mockPluginManager;
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly BookReaderRegistry _sut;
|
||||
private readonly Guid _pluginId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookReaderRegistryTests"/> class.
|
||||
/// </summary>
|
||||
public BookReaderRegistryTests()
|
||||
{
|
||||
_mockPluginManager = Substitute.For<IPluginManager>();
|
||||
_serviceProvider = new ServiceCollection().BuildServiceProvider();
|
||||
_sut = new BookReaderRegistry(_mockPluginManager, _serviceProvider);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSupportedExtensionsByPluginId_WhenReadersAreRegistered_ShouldReturnExtensionsKeyedByPluginId()
|
||||
{
|
||||
// Arrange
|
||||
IPlugin plugin = CreatePlugin(_pluginId, "Test Plugin");
|
||||
IBookReader reader = CreateReader(".epub", ".EPUB");
|
||||
_mockPluginManager.GetPlugins().Returns([plugin]);
|
||||
ServiceProvider serviceProvider = BuildServiceProviderWithReaders(plugin.Id, reader);
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = new BookReaderRegistry(_mockPluginManager, serviceProvider).GetSupportedExtensionsByPluginId();
|
||||
|
||||
// Assert
|
||||
IReadOnlyList<string> extensions = Assert.Single(result.Values);
|
||||
Assert.Equal([".epub"], extensions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSupportedExtensionsByPluginId_WhenReaderHasNoUsableExtensions_ShouldSkipThePlugin()
|
||||
{
|
||||
// Arrange
|
||||
IPlugin plugin = CreatePlugin(_pluginId, "Test Plugin");
|
||||
IBookReader reader = CreateReader(string.Empty);
|
||||
_mockPluginManager.GetPlugins().Returns([plugin]);
|
||||
ServiceProvider serviceProvider = BuildServiceProviderWithReaders(plugin.Id, reader);
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = new BookReaderRegistry(_mockPluginManager, serviceProvider).GetSupportedExtensionsByPluginId();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSupportedExtensionsByPluginId_WhenNoReadersAreRegistered_ShouldReturnEmptyDictionary()
|
||||
{
|
||||
// Arrange
|
||||
_mockPluginManager.GetPlugins().Returns([]);
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = _sut.GetSupportedExtensionsByPluginId();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSupportedExtensionsByPluginId_WhenMultipleReadersOfOnePlugin_ShouldMergeAndDistinctExtensions()
|
||||
{
|
||||
// Arrange
|
||||
IPlugin plugin = CreatePlugin(_pluginId, "Test Plugin");
|
||||
IBookReader firstReader = CreateReader(".pdf");
|
||||
IBookReader secondReader = CreateReader(".pdf", ".epub");
|
||||
_mockPluginManager.GetPlugins().Returns([plugin]);
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(plugin.Id, firstReader);
|
||||
services.AddKeyedSingleton(plugin.Id, secondReader);
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = new BookReaderRegistry(_mockPluginManager, serviceProvider).GetSupportedExtensionsByPluginId();
|
||||
|
||||
// Assert
|
||||
IReadOnlyList<string> extensions = Assert.Single(result.Values);
|
||||
Assert.Equal([".epub", ".pdf"], extensions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mocked plugin with the provided identity.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the plugin.</param>
|
||||
/// <param name="name">The name of the plugin.</param>
|
||||
/// <returns>The created plugin mock.</returns>
|
||||
private static IPlugin CreatePlugin(Guid id, string name)
|
||||
{
|
||||
IPlugin plugin = Substitute.For<IPlugin>();
|
||||
plugin.Id.Returns(id);
|
||||
plugin.Name.Returns(name);
|
||||
return plugin;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mocked book reader with the provided extensions.
|
||||
/// </summary>
|
||||
/// <param name="extensions">The supported extensions of the reader.</param>
|
||||
/// <returns>The created reader mock.</returns>
|
||||
private static IBookReader CreateReader(params string[] extensions)
|
||||
{
|
||||
IBookReader reader = Substitute.For<IBookReader>();
|
||||
reader.SupportedExtensions.Returns(extensions);
|
||||
reader.SupportedLibraryTypes.Returns([LibraryType.EBook]);
|
||||
return reader;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a service provider in which the provided readers are registered as keyed services of the plugin.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">The Id of the plugin providing the readers.</param>
|
||||
/// <param name="readers">The readers to register.</param>
|
||||
/// <returns>The built service provider.</returns>
|
||||
private static ServiceProvider BuildServiceProviderWithReaders(Guid pluginId, params IBookReader[] readers)
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
foreach (IBookReader reader in readers)
|
||||
services.AddKeyedSingleton<IBookReader>(pluginId, reader);
|
||||
return services.BuildServiceProvider();
|
||||
}
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Plugins.Contracts.Core.Plugins;
|
||||
using Lumina.Plugins.Contracts.Core.Reading;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookReadingService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookReadingServiceTests
|
||||
{
|
||||
private readonly IPluginManager _mockPluginManager;
|
||||
private readonly IPlugin _mockPlugin;
|
||||
private readonly IBookReader _mockReader;
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryBookReaderConfigurationRepository _mockConfigurationRepository;
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly BookReadingService _sut;
|
||||
private readonly BookReaderEnablementCache _enablementCache = new();
|
||||
private readonly Guid _pluginId = Guid.NewGuid();
|
||||
private readonly Guid _bookId = Guid.NewGuid();
|
||||
private readonly Guid _libraryId = Guid.NewGuid();
|
||||
private readonly string _bookPath;
|
||||
private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookReadingServiceTests"/> class.
|
||||
/// </summary>
|
||||
public BookReadingServiceTests()
|
||||
{
|
||||
_mockReader = Substitute.For<IBookReader>();
|
||||
_mockReader.SupportedExtensions.Returns([".epub"]);
|
||||
_mockReader.SupportedLibraryTypes.Returns([LibraryType.EBook]);
|
||||
_mockPlugin = Substitute.For<IPlugin>();
|
||||
_mockPlugin.Id.Returns(_pluginId);
|
||||
_mockPlugin.Name.Returns("Test Reader");
|
||||
_mockPluginManager = Substitute.For<IPluginManager>();
|
||||
_mockPluginManager.GetPlugins().Returns([_mockPlugin]);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
|
||||
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository);
|
||||
LibraryBookReaderConfigurationEntity enabledConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true);
|
||||
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(enabledConfiguration));
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(_pluginId, _mockReader);
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
IServiceScopeFactory serviceScopeFactory = _serviceProvider.GetRequiredService<IServiceScopeFactory>();
|
||||
|
||||
// The resolution and enablement guards under test stop before the book file is probed, so no real file is needed.
|
||||
_bookPath = $"lumina-test-book-{Guid.NewGuid():N}.epub";
|
||||
|
||||
_sut = new BookReadingService(_serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For<ILogger<BookReadingService>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetManifestAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPluginManager.GetPlugins().Returns([]);
|
||||
|
||||
// Act
|
||||
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError);
|
||||
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetManifestAsync_WhenReaderIsDisabledForTheLibrary_ShouldReturnReaderDisabledError()
|
||||
{
|
||||
// Arrange
|
||||
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError);
|
||||
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetManifestAsync_WhenConfigurationsReadFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Reading.Error", "Failed to read the configuration"));
|
||||
|
||||
// Act
|
||||
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("Reading.Error", result.FirstError.Code);
|
||||
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSectionAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPluginManager.GetPlugins().Returns([]);
|
||||
|
||||
// Act
|
||||
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError);
|
||||
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAvailabilityAsync_WhenReaderIsAvailableAndEnabled_ShouldReportAvailable()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
|
||||
// Act
|
||||
Result<ReadingAvailabilityResponse> result = await _sut.GetAvailabilityAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(result.Value.IsAvailable);
|
||||
Assert.Null(result.Value.ErrorCode);
|
||||
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAvailabilityAsync_WhenNoReaderSupportsTheFormat_ShouldReportUnavailableWithNoReaderAvailable()
|
||||
{
|
||||
// Arrange
|
||||
_mockPluginManager.GetPlugins().Returns([]);
|
||||
|
||||
// Act
|
||||
Result<ReadingAvailabilityResponse> result = await _sut.GetAvailabilityAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.IsAvailable);
|
||||
Assert.Equal(nameof(Errors.Reading.NoReaderAvailable), result.Value.ErrorCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAvailabilityAsync_WhenReaderIsDisabled_ShouldReportUnavailableWithReaderDisabled()
|
||||
{
|
||||
// Arrange
|
||||
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
|
||||
|
||||
// Act
|
||||
Result<ReadingAvailabilityResponse> result = await _sut.GetAvailabilityAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.False(result.Value.IsAvailable);
|
||||
Assert.Equal(nameof(Errors.Reading.ReaderDisabled), result.Value.ErrorCode);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ReadingCachePaths"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReadingCachePathsTests
|
||||
{
|
||||
[Fact]
|
||||
public void GetRootDirectory_WhenCalled_ShouldReturnBaseDirectoryWithReadingCacheDirectoryName()
|
||||
{
|
||||
// Act
|
||||
string result = ReadingCachePaths.GetRootDirectory();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(Path.Combine(AppContext.BaseDirectory, ReadingCachePaths.DIRECTORY_NAME), result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DirectoryName_WhenAccessed_ShouldReturnReadingCache()
|
||||
{
|
||||
// Assert
|
||||
Assert.Equal("reading-cache", ReadingCachePaths.DIRECTORY_NAME);
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ReadingContentSanitizer"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReadingContentSanitizerTests
|
||||
{
|
||||
[Fact]
|
||||
public void Sanitize_WhenHtmlContainsScript_ShouldStripTheScript()
|
||||
{
|
||||
// Arrange
|
||||
string html = "<section><p>Hello</p><script>alert('xss')</script></section>";
|
||||
|
||||
// Act
|
||||
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain("script", result, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("alert", result, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Hello", result, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_WhenHtmlContainsInlineEventHandler_ShouldStripTheHandler()
|
||||
{
|
||||
// Arrange
|
||||
string html = "<p onclick=\"alert('xss')\">Hello</p>";
|
||||
|
||||
// Act
|
||||
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain("onclick", result, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Hello", result, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_WhenHtmlContainsJavascriptUrl_ShouldStripTheReference()
|
||||
{
|
||||
// Arrange
|
||||
string html = "<a href=\"javascript:alert('xss')\">Link</a>";
|
||||
|
||||
// Act
|
||||
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain("javascript", result, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_WhenHtmlContainsIframe_ShouldStripTheIframe()
|
||||
{
|
||||
// Arrange
|
||||
string html = "<iframe src=\"https://evil.example\"></iframe><p>Hello</p>";
|
||||
|
||||
// Act
|
||||
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain("iframe", result, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Hello", result, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_WhenHtmlContainsDataLuminaResourceMarker_ShouldKeepTheMarker()
|
||||
{
|
||||
// Arrange
|
||||
string html = $"<img {ReadingContentSanitizer.RESOURCE_ATTRIBUTE}=\"page:1\" alt=\"Page\" />";
|
||||
|
||||
// Act
|
||||
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
|
||||
|
||||
// Assert
|
||||
Assert.Contains(ReadingContentSanitizer.RESOURCE_ATTRIBUTE, result, StringComparison.Ordinal);
|
||||
Assert.Contains("page:1", result, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_WhenHtmlContainsPlainContent_ShouldKeepTheContent()
|
||||
{
|
||||
// Arrange
|
||||
string html = "<section><h1>Chapter 1</h1><p>Some text.</p></section>";
|
||||
|
||||
// Act
|
||||
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
|
||||
|
||||
// Assert
|
||||
Assert.Contains("Chapter 1", result, StringComparison.Ordinal);
|
||||
Assert.Contains("Some text.", result, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_WhenShouldPreserveStylesIsTrue_ShouldKeepTheStyleAttribute()
|
||||
{
|
||||
// Arrange
|
||||
string html = "<p style=\"color:red\">Hello</p>";
|
||||
|
||||
// Act
|
||||
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: true);
|
||||
|
||||
// Assert
|
||||
Assert.Contains("style", result, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Hello", result, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_WhenShouldPreserveStylesIsFalse_ShouldStripTheStyleAttribute()
|
||||
{
|
||||
// Arrange
|
||||
string html = "<p style=\"color:red\">Hello</p>";
|
||||
|
||||
// Act
|
||||
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain("style", result, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("color:red", result, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Hello", result, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)] // Preserve styles.
|
||||
[InlineData(false)] // Strip styles.
|
||||
public void Sanitize_WhenHtmlContainsActiveContent_ShouldStripItRegardlessOfTheStylePreference(bool shouldPreserveStyles)
|
||||
{
|
||||
// Arrange
|
||||
string html = "<section><p style=\"color:red\">Hello</p><script>alert('xss')</script><p onclick=\"alert('xss')\">World</p></section>";
|
||||
|
||||
// Act
|
||||
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles);
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain("script", result, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("alert", result, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("onclick", result, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Hello", result, StringComparison.Ordinal);
|
||||
Assert.Contains("World", result, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // Null input.
|
||||
[InlineData("")] // Empty input.
|
||||
[InlineData(" ")] // Whitespace input.
|
||||
public void Sanitize_WhenInputIsBlank_ShouldReturnEmptyString(string? html)
|
||||
{
|
||||
// Act
|
||||
string result = ReadingContentSanitizer.Sanitize(html!, shouldPreserveStyles: false);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, result);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user