From b7db29eee58657fe2be77cd514b80d49eb8c84ed Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 9 Oct 2026 01:23:00 +0300 Subject: [PATCH] Adds the media library item deletion strategies and their domain event handler integration --- .../BooksMediaLibraryItemDeletionStrategy.cs | 88 +++++ .../IMediaLibraryItemDeletionStrategy.cs | 29 ++ .../MusicMediaLibraryItemDeletionStrategy.cs | 121 +++++++ ...braryMediaItemDeletedDomainEventHandler.cs | 57 ++- ...ksMediaLibraryItemDeletionStrategyTests.cs | 179 ++++++++++ ...icMediaLibraryItemDeletionStrategyTests.cs | 329 ++++++++++++++++++ ...MediaItemDeletedDomainEventHandlerTests.cs | 121 +++---- 7 files changed, 811 insertions(+), 113 deletions(-) create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Deletion/IMediaLibraryItemDeletionStrategy.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs new file mode 100644 index 00000000..1bab3103 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategy.cs @@ -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; + +/// +/// 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. +/// +internal sealed class BooksMediaLibraryItemDeletionStrategy : IMediaLibraryItemDeletionStrategy +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IBookArtworkService _bookArtworkService; + private readonly ILogger _logger; + + /// + /// The media library type that this deletion strategy supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for storing the artwork of the books. + /// Injected logger used to report the issues encountered while deleting the media library item. + public BooksMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, ILogger logger) + { + _unitOfWork = unitOfWork; + _bookArtworkService = bookArtworkService; + _logger = logger; + } + + /// + /// Deletes the book stored at the provided in the media library identified by , together with its stored artwork. + /// + /// The Id of the media library whose book is deleted. + /// The file system path of the book to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken) + { + // Load the book stored at the deleted path, which might have been already removed. + Result 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 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> 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 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 deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false); + if (deleteBookResult.IsFailure) + return deleteBookResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/IMediaLibraryItemDeletionStrategy.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/IMediaLibraryItemDeletionStrategy.cs new file mode 100644 index 00000000..71aeda3a --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/IMediaLibraryItemDeletionStrategy.cs @@ -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; + +/// +/// 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. +/// +public interface IMediaLibraryItemDeletionStrategy +{ + /// + /// The media library type that this deletion strategy supports. + /// + LibraryType SupportedLibraryType { get; } + + /// + /// Deletes the media library item stored at the provided in the media library identified by . + /// + /// The Id of the media library whose item is deleted. + /// The file system path of the media library item to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs new file mode 100644 index 00000000..7acb3af4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategy.cs @@ -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; + +/// +/// 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. +/// +internal sealed class MusicMediaLibraryItemDeletionStrategy : IMediaLibraryItemDeletionStrategy +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// The media library type that this deletion strategy supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Music; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public MusicMediaLibraryItemDeletionStrategy(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Deletes the track stored at the provided in the media library identified by , together with its stored artwork, + /// and the album and the artist that are left with no children after the removal. + /// + /// The Id of the media library whose track is deleted. + /// The file system path of the track to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteItemAsync(Guid libraryId, string path, CancellationToken cancellationToken) + { + // Load the track stored at the deleted path, which might have been already removed. + Result 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 deleteTrackArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, cancellationToken).ConfigureAwait(false); + if (deleteTrackArtworkResult.IsFailure) + return deleteTrackArtworkResult.Errors; + + Result 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 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> 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 deleteAlbumArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false); + if (deleteAlbumArtworkResult.IsFailure) + return deleteAlbumArtworkResult.Errors; + + Result deleteAlbumResult = await _unitOfWork.AlbumRepository.DeleteByIdAsync(albumId, cancellationToken).ConfigureAwait(false); + if (deleteAlbumResult.IsFailure) + return deleteAlbumResult.Errors; + + Result> 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 deleteArtistArtworkResult = await _unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false); + if (deleteArtistArtworkResult.IsFailure) + return deleteArtistArtworkResult.Errors; + + Result deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false); + if (deleteArtistResult.IsFailure) + return deleteArtistResult.Errors; + } + } + + return await SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Persists the changes made to the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> SaveChangesAsync(CancellationToken cancellationToken) + { + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return saveChangesResult.IsFailure ? saveChangesResult.Errors : Result.Success; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs index 7c68e86b..8d63a811 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs @@ -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; /// /// 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. /// public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler { private readonly IUnitOfWork _unitOfWork; - private readonly IBookArtworkService _bookArtworkService; + private readonly IEnumerable _mediaLibraryItemDeletionStrategies; private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - /// Injected service for storing the artwork of the books. + /// Injected deletion strategies, one for each supported media library type. /// Injected logger used to report the issues encountered while deleting the media library item. - public LibraryMediaItemDeletedDomainEventHandler(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, ILogger logger) + public LibraryMediaItemDeletedDomainEventHandler(IUnitOfWork unitOfWork, IEnumerable mediaLibraryItemDeletionStrategies, ILogger logger) { _unitOfWork = unitOfWork; - _bookArtworkService = bookArtworkService; + _mediaLibraryItemDeletionStrategies = mediaLibraryItemDeletionStrategies; _logger = logger; } @@ -48,36 +50,23 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler 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 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> 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 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 deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(book.Id, cancellationToken).ConfigureAwait(false); - if (deleteBookResult.IsFailure) - throw new EventualConsistencyException(deleteBookResult.FirstError, deleteBookResult.Errors); - - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); + Result deleteItemResult = await deletionStrategy.DeleteItemAsync(libraryId, domainEvent.Path, cancellationToken).ConfigureAwait(false); + if (deleteItemResult.IsFailure) + throw new EventualConsistencyException(deleteItemResult.FirstError, deleteItemResult.Errors); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs new file mode 100644 index 00000000..c054f80b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/BooksMediaLibraryItemDeletionStrategyTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksMediaLibraryItemDeletionStrategyTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IBookArtworkService _mockBookArtworkService; + private readonly ILogger _mockLogger; + private readonly BooksMediaLibraryItemDeletionStrategy _sut; + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public BooksMediaLibraryItemDeletionStrategyTests() + { + _mockUnitOfWork = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + + _mockBookArtworkService = Substitute.For(); + _mockLogger = Substitute.For>(); + + _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()) + .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result 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()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenNoBookExistsAtPath_ShouldDoNothing() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + _mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork")); + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result 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()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(error); + + // Act + Result 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(), Arg.Any()); + } + + [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()) + .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + Error error = Error.Failure("Database.Error", "Failed to delete the book"); + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) + .Returns(error); + + // Act + Result 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()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs new file mode 100644 index 00000000..8a96de2f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Deletion/MusicMediaLibraryItemDeletionStrategyTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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(); + + /// + /// Initializes a new instance of the class. + /// + public MusicMediaLibraryItemDeletionStrategyTests() + { + _mockUnitOfWork = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockMusicArtworkRepository = Substitute.For(); + _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()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([otherTrack])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result 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()); + await _mockTrackRepository.Received(1).DeleteByIdAsync(track.Id, Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Album, Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.Deleted); + _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(Result.From>([otherAlbum])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result 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()); + await _mockAlbumRepository.Received(1).DeleteByIdAsync(albumId, Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.Deleted); + _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(Result.From>([album])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtistRepository.DeleteByIdAsync(artistId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result 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()); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()); + await _mockAlbumRepository.Received(1).DeleteByIdAsync(albumId, Arg.Any()); + await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + await _mockTrackRepository.Received(1).DeleteByIdAsync(track.Id, Arg.Any()); + await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task DeleteItemAsync_WhenNoTrackExistsAtPath_ShouldDoNothing() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + _mockTrackRepository.GetByPathAsync(libraryId.Value, "/music/deleted.flac", Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.DeleteItemAsync(libraryId.Value, "/music/deleted.flac", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(error); + + // Act + Result 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(), Arg.Any()); + } + + [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()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(error); + + // Act + Result 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(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(error); + + // Act + Result 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(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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()) + .Returns(Result.From(track)); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByIdAsync(albumId, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>([track])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any()) + .Returns(Result.Deleted); + _mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(Result.From>([album])); + _mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any()) + .Returns(error); + + // Act + Result 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(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs index 18d28223..644b8b6f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs @@ -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 _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(); - _mockBookRepository = Substitute.For(); _mockLibraryRepository = Substitute.For(); - _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); - _mockBookArtworkService = Substitute.For(); + _mockDeletionStrategy = Substitute.For(); _mockLogger = Substitute.For>(); - _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()) - .Returns(Result.From(book)); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, libraryType: LibraryType.Book); _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) - .Returns(Result.From(Result.Deleted)); - _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).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()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenNoBookExistsAtPath_ShouldDoNothing() - { - // Arrange - LibraryId libraryId = _libraryIdFixture.Create(); - _mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) - .Returns(Result.From(null)); + _mockDeletionStrategy.SupportedLibraryType.Returns(LibraryType.Book); + _mockDeletionStrategy.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) + .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(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockDeletionStrategy.Received(1).DeleteItemAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()); } [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()) - .Returns(Result.From(book)); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, libraryType: LibraryType.Music); _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork")); - _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) - .Returns(Result.From(Result.Deleted)); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).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()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockDeletionStrategy.DidNotReceive().DeleteItemAsync(Arg.Any(), Arg.Any(), Arg.Any()); } [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()) + Error error = Error.Failure("Database.Error", "Failed to get the library"); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) .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(), Arg.Any()); + await _mockDeletionStrategy.DidNotReceive().DeleteItemAsync(Arg.Any(), Arg.Any(), Arg.Any()); } [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()) - .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: "/books/deleted.epub"); + + // Act & Assert + await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + await _mockDeletionStrategy.DidNotReceive().DeleteItemAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [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()) .Returns(Result.From(library)); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.Deleted); - Error error = Error.Failure("Database.Error", "Failed to delete the book"); - _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) + _mockDeletionStrategy.SupportedLibraryType.Returns(LibraryType.Book); + _mockDeletionStrategy.DeleteItemAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) .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( @@ -185,6 +149,5 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert Assert.Equal(error, exception.EventualConsistencyError); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } }