Adds the media library item deletion strategies and their domain event handler integration

This commit is contained in:
BinaryAlley committed 2026-10-09 01:23:00 +03:00
1 parent 35ac1dbdcb
commit b7db29eee5
7 files changed
+811 -113

No files matched your search

@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Deletion;
/// <summary>
/// Deletion strategy for the media library items of the books media library type. The book stored at the deleted path is removed, together with its stored artwork.
/// </summary>
internal sealed class BooksMediaLibraryItemDeletionStrategy : IMediaLibraryItemDeletionStrategy
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBookArtworkService _bookArtworkService;
private readonly ILogger<BooksMediaLibraryItemDeletionStrategy> _logger;
/// <summary>
/// The media library type that this deletion strategy supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Book;
/// <summary>
/// Initializes a new instance of the <see cref="BooksMediaLibraryItemDeletionStrategy"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="bookArtworkService">Injected service for storing the artwork of the books.</param>
/// <param name="logger">Injected logger used to report the issues encountered while deleting the media library item.</param>
public BooksMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, ILogger<BooksMediaLibraryItemDeletionStrategy> logger)
{
_unitOfWork = unitOfWork;
_bookArtworkService = bookArtworkService;
_logger = logger;
}
/// <summary>
/// Deletes the book stored at the provided <paramref name="path"/> in the media library identified by <paramref name="libraryId"/>, together with its stored artwork.
/// </summary>
/// <param name="libraryId">The Id of the media library whose book is deleted.</param>
/// <param name="path">The file system path of the book to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken)
{
// Load the book stored at the deleted path, which might have been already removed.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByPathAsync(libraryId, path, cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
return getBookResult.Errors;
BookEntity? book = getBookResult.Value;
if (book is null)
return Result.Success;
// Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
return getLibraryResult.IsFailure ? getLibraryResult.Errors : Errors.Library.LibraryNotFound;
LibraryEntity library = getLibraryResult.Value;
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await _unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([book.Id], cancellationToken).ConfigureAwait(false);
if (getAuthorsResult.IsFailure)
return getAuthorsResult.Errors;
string authorName = getAuthorsResult.Value.TryGetValue(book.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty;
Result<Deleted> deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, book.Id, library.Title, authorName, book.Title);
if (deleteArtworkResult.IsFailure)
_logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path);
// Delete the book, whose stored artwork and participations are removed by the database cascade.
Result<Deleted> deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false);
if (deleteBookResult.IsFailure)
return deleteBookResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Success;
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Deletion;
/// <summary>
/// Interface defining the strategy used to delete a media library item that is no longer present in the media library scan snapshot, for a specific media library type.
/// </summary>
public interface IMediaLibraryItemDeletionStrategy
{
/// <summary>
/// The media library type that this deletion strategy supports.
/// </summary>
LibraryType SupportedLibraryType { get; }
/// <summary>
/// Deletes the media library item stored at the provided <paramref name="path"/> in the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose item is deleted.</param>
/// <param name="path">The file system path of the media library item to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken);
}
@@ -0,0 +1,121 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Deletion;
/// <summary>
/// Deletion strategy for the media library items of the music media library type. The track stored at the deleted path is removed, together with its stored artwork,
/// and the album and the artist that are left with no children after the removal are removed as well.
/// </summary>
internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemDeletionStrategy
{
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// The media library type that this deletion strategy supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Music;
/// <summary>
/// Initializes a new instance of the <see cref="MusicMediaLibraryItemDeletionStrategy"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public MusicMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Deletes the track stored at the provided <paramref name="path"/> in the media library identified by <paramref name="libraryId"/>, together with its stored artwork,
/// and the album and the artist that are left with no children after the removal.
/// </summary>
/// <param name="libraryId">The Id of the media library whose track is deleted.</param>
/// <param name="path">The file system path of the track to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken)
{
// Load the track stored at the deleted path, which might have been already removed.
Result<TrackEntity?> getTrackResult = await _unitOfWork.TrackRepository.GetByPathAsync(libraryId, path, cancellationToken).ConfigureAwait(false);
if (getTrackResult.IsFailure)
return getTrackResult.Errors;
TrackEntity? track = getTrackResult.Value;
if (track is null)
return Result.Success;
Guid trackId = track.Id;
Guid albumId = track.AlbumId;
// Delete the stored artwork of the track, which has no cascade relationship because the artwork table is shared by all the music library item types.
Result<Deleted> deleteTrackArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken).ConfigureAwait(false);
if (deleteTrackArtworkResult.IsFailure)
return deleteTrackArtworkResult.Errors;
Result<Deleted> deleteTrackResult = await _unitOfWork.TrackRepository.DeleteByIdAsync(trackId, cancellationToken).ConfigureAwait(false);
if (deleteTrackResult.IsFailure)
return deleteTrackResult.Errors;
// Load the album the deleted track belonged to, to determine whether it is left with no children.
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
AlbumEntity? album = getAlbumResult.Value;
if (album is null)
return await SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Guid artistId = album.ArtistId;
Result<IReadOnlyList<TrackEntity>> getRemainingTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(albumId, cancellationToken).ConfigureAwait(false);
if (getRemainingTracksResult.IsFailure)
return getRemainingTracksResult.Errors;
// The deleted track is still tracked by the change tracker until the changes are saved, so it is excluded explicitly.
if (getRemainingTracksResult.Value.All(remainingTrack => remainingTrack.Id == trackId))
{
Result<Deleted> deleteAlbumArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
if (deleteAlbumArtworkResult.IsFailure)
return deleteAlbumArtworkResult.Errors;
Result<Deleted> deleteAlbumResult = await _unitOfWork.AlbumRepository.DeleteByIdAsync(albumId, cancellationToken).ConfigureAwait(false);
if (deleteAlbumResult.IsFailure)
return deleteAlbumResult.Errors;
Result<IReadOnlyList<AlbumEntity>> getRemainingAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (getRemainingAlbumsResult.IsFailure)
return getRemainingAlbumsResult.Errors;
// The deleted album is still tracked by the change tracker until the changes are saved, so it is excluded explicitly.
if (getRemainingAlbumsResult.Value.All(remainingAlbum => remainingAlbum.Id == albumId))
{
Result<Deleted> deleteArtistArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtistArtworkResult.IsFailure)
return deleteArtistArtworkResult.Errors;
Result<Deleted> deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false);
if (deleteArtistResult.IsFailure)
return deleteArtistResult.Errors;
}
}
return await SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Persists the changes made to the storage medium.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> SaveChangesAsync(CancellationToken cancellationToken)
{
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return saveChangesResult.IsFailure ? saveChangesResult.Errors : Result.Success;
}
}
@@ -1,15 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.Management.Deletion;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -18,24 +20,24 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the domain event raised when a media library item is no longer present in the media library scan snapshot.
/// The book stored at the deleted path is removed, together with its stored artwork.
/// The media library item stored at the deleted path is removed by the deletion strategy of the media library type it belongs to.
/// </summary>
public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler<LibraryMediaItemDeletedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBookArtworkService _bookArtworkService;
private readonly IEnumerable<IMediaLibraryItemDeletionStrategy> _mediaLibraryItemDeletionStrategies;
private readonly ILogger<LibraryMediaItemDeletedDomainEventHandler> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMediaItemDeletedDomainEventHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="bookArtworkService">Injected service for storing the artwork of the books.</param>
/// <param name="mediaLibraryItemDeletionStrategies">Injected deletion strategies, one for each supported media library type.</param>
/// <param name="logger">Injected logger used to report the issues encountered while deleting the media library item.</param>
public LibraryMediaItemDeletedDomainEventHandler(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, ILogger<LibraryMediaItemDeletedDomainEventHandler> logger)
public LibraryMediaItemDeletedDomainEventHandler(IUnitOfWork unitOfWork, IEnumerable<IMediaLibraryItemDeletionStrategy> mediaLibraryItemDeletionStrategies, ILogger<LibraryMediaItemDeletedDomainEventHandler> logger)
{
_unitOfWork = unitOfWork;
_bookArtworkService = bookArtworkService;
_mediaLibraryItemDeletionStrategies = mediaLibraryItemDeletionStrategies;
_logger = logger;
}
@@ -48,36 +50,23 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler<Lib
{
Guid libraryId = domainEvent.LibraryId.Value;
// Load the book stored at the deleted path, which might have been already removed.
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByPathAsync(libraryId, domainEvent.Path, cancellationToken).ConfigureAwait(false);
if (getBookResult.IsFailure)
throw new EventualConsistencyException(getBookResult.FirstError, getBookResult.Errors);
BookEntity? book = getBookResult.Value;
if (book is null)
return;
// Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed.
// Load the media library, whose type determines the deletion strategy to use.
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
if (getLibraryResult.IsFailure)
throw new EventualConsistencyException(getLibraryResult.FirstError, getLibraryResult.Errors);
LibraryEntity library = getLibraryResult.Value;
if (getLibraryResult.Value is null)
throw new EventualConsistencyException(Errors.Library.LibraryNotFound);
LibraryType libraryType = getLibraryResult.Value.LibraryType;
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await _unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([book.Id], cancellationToken).ConfigureAwait(false);
if (getAuthorsResult.IsFailure)
throw new EventualConsistencyException(getAuthorsResult.FirstError, getAuthorsResult.Errors);
string authorName = getAuthorsResult.Value.TryGetValue(book.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty;
IMediaLibraryItemDeletionStrategy? deletionStrategy = _mediaLibraryItemDeletionStrategies.FirstOrDefault(strategy => strategy.SupportedLibraryType == libraryType);
if (deletionStrategy is null)
{
_logger.LogWarning("No deletion strategy exists for media library type '{LibraryType}', the item at path '{ItemPath}' was not deleted.", libraryType, domainEvent.Path);
return;
}
Result<Deleted> deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, book.Id, library.Title, authorName, book.Title);
if (deleteArtworkResult.IsFailure)
_logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path);
// Delete the book, whose stored artwork and participations are removed by the database cascade.
Result<Deleted> deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false);
if (deleteBookResult.IsFailure)
throw new EventualConsistencyException(deleteBookResult.FirstError, deleteBookResult.Errors);
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors);
Result<Success> deleteItemResult = await deletionStrategy.DeleteItemAsync(libraryId, domainEvent.Path, cancellationToken).ConfigureAwait(false);
if (deleteItemResult.IsFailure)
throw new EventualConsistencyException(deleteItemResult.FirstError, deleteItemResult.Errors);
}
}
@@ -0,0 +1,179 @@
#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.Core.MediaLibrary.Management.Deletion;
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.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
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.Application.UnitTests.Core.MediaLibrary.Management.Deletion;
/// <summary>
/// Contains unit tests for the <see cref="BooksMediaLibraryItemDeletionStrategy"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BooksMediaLibraryItemDeletionStrategyTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IBookArtworkService _mockBookArtworkService;
private readonly ILogger<BooksMediaLibraryItemDeletionStrategy> _mockLogger;
private readonly BooksMediaLibraryItemDeletionStrategy _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BooksMediaLibraryItemDeletionStrategyTests"/> class.
/// </summary>
public BooksMediaLibraryItemDeletionStrategyTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
_mockLogger = Substitute.For<ILogger<BooksMediaLibraryItemDeletionStrategy>>();
_sut = new BooksMediaLibraryItemDeletionStrategy(_mockUnitOfWork, _mockBookArtworkService, _mockLogger);
}
[Fact]
public async Task DeleteItemAsync_WhenBookExistsAtPath_ShouldDeleteTheBookAndItsArtwork()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
_mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Result.Deleted);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, book.Path, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
_mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId.Value, book.Id, "My Library", "Frank Herbert", book.Title);
await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenNoBookExistsAtPath_ShouldDoNothing()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork"));
_mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, book.Path, CancellationToken.None);
// Assert
// a failing artwork deletion must not prevent the book from being removed, so the deletion is only logged
Assert.True(result.IsSuccess);
await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenGetBookFails_ShouldReturnFailure()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the book");
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenDeleteBookFails_ShouldReturnFailure()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Result.Deleted);
Error error = Error.Failure("Database.Error", "Failed to delete the book");
_mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, book.Path, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,329 @@
#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.Core.MediaLibrary.Management.Deletion;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Deletion;
/// <summary>
/// Contains unit tests for the <see cref="MusicMediaLibraryItemDeletionStrategy"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicMediaLibraryItemDeletionStrategyTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ITrackRepository _mockTrackRepository;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly IArtistRepository _mockArtistRepository;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly MusicMediaLibraryItemDeletionStrategy _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MusicMediaLibraryItemDeletionStrategyTests"/> class.
/// </summary>
public MusicMediaLibraryItemDeletionStrategyTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockTrackRepository = Substitute.For<ITrackRepository>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_sut = new MusicMediaLibraryItemDeletionStrategy(_mockUnitOfWork);
}
[Fact]
public async Task DeleteItemAsync_WhenAlbumHasOtherTracks_ShouldDeleteOnlyTheTrackAndItsArtwork()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Guid albumId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac");
AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false);
TrackEntity otherTrack = _trackEntityFixture.Create(albumId: albumId);
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([otherTrack]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>());
await _mockTrackRepository.Received(1).DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Album, Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenAlbumHasNoOtherTracksButArtistHasOtherAlbums_ShouldDeleteTheAlbumAndItsArtwork()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac");
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false);
AlbumEntity otherAlbum = _albumEntityFixture.Create(artistId: artistId, includeTracks: false);
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([otherAlbum]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>());
await _mockAlbumRepository.Received(1).DeleteByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenAlbumAndArtistAreLeftWithNoChildren_ShouldDeleteTheTrackAlbumAndArtist()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac");
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false);
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtistRepository.DeleteByIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>());
await _mockAlbumRepository.Received(1).DeleteByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenAlbumWasAlreadyRemoved_ShouldPersistTheTrackDeletion()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Guid albumId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac");
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(null));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
await _mockTrackRepository.Received(1).DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenNoTrackExistsAtPath_ShouldDoNothing()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
_mockTrackRepository.GetByPathAsync(libraryId.Value, "/music/deleted.flac", Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(null));
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, "/music/deleted.flac", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenGetTrackFails_ShouldReturnFailure()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the track");
_mockTrackRepository.GetByPathAsync(libraryId.Value, "/music/deleted.flac", Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, "/music/deleted.flac", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenDeleteTrackArtworkFails_ShouldReturnFailure()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Guid albumId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac");
Error error = Error.Failure("Database.Error", "Failed to delete the track artwork");
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenDeleteAlbumArtworkFails_ShouldReturnFailure()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac");
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false);
Error error = Error.Failure("Database.Error", "Failed to delete the album artwork");
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenDeleteArtistArtworkFails_ShouldReturnFailure()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/deleted.flac");
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, includeTracks: false);
Error error = Error.Failure("Database.Error", "Failed to delete the artist artwork");
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,23 +1,20 @@
#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.Core.MediaLibrary.Management.Deletion;
using Lumina.Application.Core.MediaLibrary.Management.Events;
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.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
@@ -32,13 +29,11 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events;
public class LibraryMediaItemDeletedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IBookArtworkService _mockBookArtworkService;
private readonly IMediaLibraryItemDeletionStrategy _mockDeletionStrategy;
private readonly ILogger<LibraryMediaItemDeletedDomainEventHandler> _mockLogger;
private readonly LibraryMediaItemDeletedDomainEventHandler _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMediaItemDeletedDomainEventFixture _libraryMediaItemDeletedDomainEventFixture = new();
@@ -48,54 +43,26 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
public LibraryMediaItemDeletedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
_mockDeletionStrategy = Substitute.For<IMediaLibraryItemDeletionStrategy>();
_mockLogger = Substitute.For<ILogger<LibraryMediaItemDeletedDomainEventHandler>>();
_sut = new LibraryMediaItemDeletedDomainEventHandler(_mockUnitOfWork, _mockBookArtworkService, _mockLogger);
_sut = new LibraryMediaItemDeletedDomainEventHandler(_mockUnitOfWork, [_mockDeletionStrategy], _mockLogger);
}
[Fact]
public async Task HandleAsync_WhenBookExistsAtPath_ShouldDeleteTheBookAndItsArtwork()
public async Task HandleAsync_WhenDeletionStrategyExistsForTheLibraryType_ShouldDelegateToIt()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, libraryType: LibraryType.Book);
_mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
_mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Result.Deleted);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
_mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId.Value, book.Id, "My Library", "Frank Herbert", book.Title);
await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenNoBookExistsAtPath_ShouldDoNothing()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(null));
_mockDeletionStrategy.SupportedLibraryType.Returns(LibraryType.Book);
_mockDeletionStrategy.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(Result.Success);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub");
@@ -103,48 +70,35 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
_mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDeletionStrategy.Received(1).DeleteItemAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook()
public async Task HandleAsync_WhenNoDeletionStrategyExistsForTheLibraryType_ShouldNotDelete()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, libraryType: LibraryType.Music);
_mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork"));
_mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockDeletionStrategy.SupportedLibraryType.Returns(LibraryType.Book);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/music/deleted.flac");
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
// a failing artwork deletion must not prevent the book from being removed, so the deletion is only logged
await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDeletionStrategy.DidNotReceive().DeleteItemAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetBookFails_ShouldThrowEventualConsistencyException()
public async Task HandleAsync_WhenGetLibraryFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the book");
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
Error error = Error.Failure("Database.Error", "Failed to get the library");
_mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(error);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub");
@@ -155,29 +109,39 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockDeletionStrategy.DidNotReceive().DeleteItemAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeleteBookFails_ShouldThrowEventualConsistencyException()
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub");
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library");
_mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<BookEntity?>(book));
_mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub");
// Act & Assert
await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
await _mockDeletionStrategy.DidNotReceive().DeleteItemAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletionFails_ShouldThrowEventualConsistencyException()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, libraryType: LibraryType.Book);
Error error = Error.Failure("Database.Error", "Failed to delete the item");
_mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(Result.Deleted);
Error error = Error.Failure("Database.Error", "Failed to delete the book");
_mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any<CancellationToken>())
_mockDeletionStrategy.SupportedLibraryType.Returns(LibraryType.Book);
_mockDeletionStrategy.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
.Returns(error);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path);
LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub");
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
@@ -185,6 +149,5 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}