Cleans up the artwork and the stored media of deleted music library items and libraries.

This commit is contained in:
BinaryAlley committed 2026-10-13 13:26:26 +03:00
1 parent 9d82f283e4
commit 4f43bf352b
23 files changed
+1390 -74

No files matched your search

@@ -442,6 +442,38 @@ public class BookRepositoryTests
Assert.Equal(keptContributor.Id, Assert.Single(storedBook.Contributors).Id);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldDeleteOnlyThatLibrariesBooks()
{
// Arrange
// The delete uses ExecuteDeleteAsync, which is not supported by the in-memory provider, so a real SQLite database is used.
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-deletebylibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
BookEntity bookOfLibrary = _bookEntityFixture.Create();
bookOfLibrary.LibraryId = libraryId;
bookOfLibrary.Path = "/books/library.epub";
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.Path = "/books/other.epub";
context.Books.AddRange(bookOfLibrary, bookOfAnotherLibrary);
await context.SaveChangesAsync();
// Act
Result<Deleted> result = await sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
context.ChangeTracker.Clear();
BookEntity survivor = Assert.Single(await context.Books.AsNoTracking().ToListAsync());
Assert.Equal(bookOfAnotherLibrary.Id, survivor.Id);
}
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
@@ -5,6 +5,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioL
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -37,6 +38,8 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
@@ -77,6 +80,28 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == otherAlbumId));
}
[Fact]
public async Task DeleteAlbum_WhenAlbumHasStoredArtwork_ShouldRemoveTheArtworkOfTheAlbumAndOfItsTracks()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId);
await SeedArtworkAsync(MusicArtworkOwnerType.Album, albumId, "media/music/queen/album.jpg");
await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/track.jpg");
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// The artwork of the album and of its tracks does not cascade from the album row, so it is removed together with the album.
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId));
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
}
[Fact]
public async Task DeleteAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
{
@@ -184,6 +209,74 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(
id: trackId,
albumId: albumId,
libraryId: libraryId,
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
AlbumEntity album = _albumEntityFixture.Create(
id: albumId,
artistId: artistId,
libraryId: libraryId,
title: "A Night at the Opera",
tracks: [track],
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
// An artist must keep at least one album, so a sibling album is seeded alongside the deleted one.
AlbumEntity otherAlbum = _albumEntityFixture.Create(
id: Guid.NewGuid(),
artistId: artistId,
libraryId: libraryId,
title: "News of the World",
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId, trackId);
}
/// <summary>
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored artwork.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
await dbContext.SaveChangesAsync();
}
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
@@ -1,9 +1,11 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -35,6 +37,9 @@ public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
@@ -73,6 +78,33 @@ public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
Assert.Null(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId));
}
[Fact]
public async Task DeleteArtist_WhenArtistHasStoredArtwork_ShouldRemoveTheArtworkOfTheArtistAndOfItsChildren()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId);
await SeedArtworkAsync(MusicArtworkOwnerType.Artist, artistId, "media/music/queen/artist.jpg");
await SeedArtworkAsync(MusicArtworkOwnerType.Album, albumId, "media/music/queen/album.jpg");
await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/track.jpg");
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// The artist takes its albums and their tracks with it, and the artwork of all of them does not cascade, so it is removed together with the artist.
Assert.Null(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId));
Assert.Null(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId));
Assert.Null(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId));
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId));
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId));
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
}
[Fact]
public async Task DeleteArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
{
@@ -163,6 +195,61 @@ public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(
id: trackId,
albumId: albumId,
libraryId: libraryId,
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
AlbumEntity album = _albumEntityFixture.Create(
id: albumId,
artistId: artistId,
libraryId: libraryId,
title: "A Night at the Opera",
tracks: [track],
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId, trackId);
}
/// <summary>
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored artwork.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
await dbContext.SaveChangesAsync();
}
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
@@ -6,12 +6,14 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioL
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
@@ -40,6 +42,7 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
@@ -81,6 +84,26 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
Assert.NotNull(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId));
}
[Fact]
public async Task DeleteTrack_WhenTrackHasStoredArtwork_ShouldRemoveItsArtworkRecords()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, "Bohemian Rhapsody", "/music/queen/bohemian-rhapsody.flac");
await SeedArtworkAsync(MusicArtworkOwnerType.Track, trackId, "media/music/queen/bohemian-rhapsody.jpg");
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// The artwork of the track does not cascade from the track row, so it is removed together with the track.
Assert.Null(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
}
[Fact]
public async Task DeleteTrack_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
{
@@ -229,10 +252,12 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
using JsonDocument problemDetails = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("General.Unauthorized", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("NotAuthorized", problemDetails.RootElement.GetProperty("detail").GetString());
Assert.DoesNotContain("Exception", problemDetails.RootElement.GetRawText(), StringComparison.Ordinal);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Fact]
@@ -258,8 +283,9 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// The route value is kept as a raw string, so the unparseable Id reaches the command validator, which reports a clean validation error instead of failing the request binding.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
@@ -272,8 +298,9 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
@@ -286,8 +313,9 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
Assert.Contains("AlbumIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
@@ -300,11 +328,27 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Validation", problemDetails!["title"].GetString());
Assert.Contains("TrackIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a piece of stored artwork owned by the music library item identified by <paramref name="ownerId"/>.
/// </summary>
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
/// <param name="fileName">The relative file name of the stored artwork.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtworkAsync(MusicArtworkOwnerType ownerType, Guid ownerId, string fileName)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, fileName: fileName));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
@@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
@@ -35,6 +36,7 @@ public class DeleteAlbumCommandHandlerTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<DeleteAlbumCommand> _mockValidator;
@@ -55,24 +57,27 @@ public class DeleteAlbumCommandHandlerTests
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockMusicArtworkCleanupService = Substitute.For<IMusicArtworkCleanupService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<DeleteAlbumCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist update succeeds and saving changes succeeds.
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist update succeeds, the artwork cleanup succeeds and saving changes succeeds.
_mockValidator.Validate(Arg.Any<DeleteAlbumCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
_mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new DeleteAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
_sut = new DeleteAlbumCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
@@ -92,6 +97,13 @@ public class DeleteAlbumCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
// The artwork of the album and of its tracks is removed before the album is removed from the artist aggregate, so that no artwork is orphaned.
await _mockMusicArtworkCleanupService.Received(1).DeleteAlbumArtworkAsync(albumId, Arg.Any<CancellationToken>());
Received.InOrder(() =>
{
_mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, Arg.Any<CancellationToken>());
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
});
await _mockArtistRepository.Received(1).UpdateAsync(
Arg.Is<ArtistEntity>(updatedArtist =>
updatedArtist.Id == artistId &&
@@ -117,6 +129,7 @@ public class DeleteAlbumCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.AlbumIdCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkCleanupService.DidNotReceive().DeleteAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -323,6 +336,30 @@ public class DeleteAlbumCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError);
await _mockMusicArtworkCleanupService.DidNotReceive().DeleteAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutUpdatingTheArtist()
{
// Arrange
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid()));
Error error = Error.Failure(description: "Failed to delete the artwork");
_mockMusicArtworkCleanupService.DeleteAlbumArtworkAsync(albumId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist;
@@ -33,6 +34,7 @@ public class DeleteArtistCommandHandlerTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<DeleteArtistCommand> _mockValidator;
@@ -52,24 +54,27 @@ public class DeleteArtistCommandHandlerTests
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockMusicArtworkCleanupService = Substitute.For<IMusicArtworkCleanupService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<DeleteArtistCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist deletion succeeds and saving changes succeeds.
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist deletion succeeds, the artwork cleanup succeeds and saving changes succeeds.
_mockValidator.Validate(Arg.Any<DeleteArtistCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
_mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtistRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new DeleteArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
_sut = new DeleteArtistCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
@@ -89,6 +94,13 @@ public class DeleteArtistCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
// The artwork of the artist and of its albums and tracks is removed before the artist row, so that no artwork is orphaned.
await _mockMusicArtworkCleanupService.Received(1).DeleteArtistArtworkAsync(artistId, Arg.Any<CancellationToken>());
Received.InOrder(() =>
{
_mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, Arg.Any<CancellationToken>());
_mockArtistRepository.DeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
});
await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
@@ -110,6 +122,7 @@ public class DeleteArtistCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistIdCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkCleanupService.DidNotReceive().DeleteArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -259,6 +272,30 @@ public class DeleteArtistCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutDeletingTheArtist()
{
// Arrange
DeleteArtistCommand command = _deleteArtistCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
Error error = Error.Failure(description: "Failed to delete the artwork");
_mockMusicArtworkCleanupService.DeleteArtistArtworkAsync(artistId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, 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>());
}
[Fact]
public async Task HandleAsync_WhenDeleteArtistFails_ShouldReturnErrorWithoutSaving()
{
@@ -0,0 +1,324 @@
#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.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.Common.Primitives;
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;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
/// <summary>
/// Contains unit tests for the <see cref="MusicArtworkCleanupService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicArtworkCleanupServiceTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly ITrackRepository _mockTrackRepository;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly IMusicArtworkService _mockMusicArtworkService;
private readonly MusicArtworkCleanupService _sut;
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MusicArtworkCleanupServiceTests"/> class.
/// </summary>
public MusicArtworkCleanupServiceTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockTrackRepository = Substitute.For<ITrackRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
// Default stubs: every owner has no artwork, deleting the records succeeds, deleting a stored file succeeds.
_mockAlbumRepository.GetByArtistIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([]));
_mockTrackRepository.GetByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([]));
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockMusicArtworkService.DeleteStoredArtwork(Arg.Any<string>()).Returns(Result.Deleted);
_sut = new MusicArtworkCleanupService(_mockUnitOfWork, _mockMusicArtworkService);
}
[Fact]
public async Task DeleteArtistArtworkAsync_WhenArtistHasAlbumsAndTracks_ShouldRemoveTheArtworkOfTheChildrenBeforeTheArtistArtwork()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid firstAlbumId = Guid.NewGuid();
Guid secondAlbumId = Guid.NewGuid();
Guid firstTrackId = Guid.NewGuid();
Guid secondTrackId = Guid.NewGuid();
Guid thirdTrackId = Guid.NewGuid();
AlbumEntity firstAlbum = _albumEntityFixture.Create(id: firstAlbumId, includeTracks: false);
AlbumEntity secondAlbum = _albumEntityFixture.Create(id: secondAlbumId, includeTracks: false);
TrackEntity firstTrack = _trackEntityFixture.Create(id: firstTrackId, albumId: firstAlbumId);
TrackEntity secondTrack = _trackEntityFixture.Create(id: secondTrackId, albumId: firstAlbumId);
TrackEntity thirdTrack = _trackEntityFixture.Create(id: thirdTrackId, albumId: secondAlbumId);
MusicArtworkEntity firstTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: firstTrackId, fileName: "/media/music/first-track.jpg");
MusicArtworkEntity secondTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: secondTrackId, fileName: "/media/music/second-track.jpg");
MusicArtworkEntity thirdTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: thirdTrackId, fileName: "/media/music/third-track.jpg");
MusicArtworkEntity firstAlbumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: firstAlbumId, fileName: "/media/music/first-album.jpg");
MusicArtworkEntity secondAlbumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: secondAlbumId, fileName: "/media/music/second-album.jpg");
MusicArtworkEntity artistArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, fileName: "/media/music/artist.jpg");
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([firstAlbum, secondAlbum]));
_mockTrackRepository.GetByAlbumIdAsync(firstAlbumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([firstTrack, secondTrack]));
_mockTrackRepository.GetByAlbumIdAsync(secondAlbumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([thirdTrack]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([firstTrackArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([secondTrackArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, thirdTrackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([thirdTrackArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, firstAlbumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([firstAlbumArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, secondAlbumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([secondAlbumArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([artistArtwork]));
// Act
Result<Deleted> result = await _sut.DeleteArtistArtworkAsync(artistId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(firstTrackArtwork.FileName!);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(secondTrackArtwork.FileName!);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(thirdTrackArtwork.FileName!);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(firstAlbumArtwork.FileName!);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(secondAlbumArtwork.FileName!);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(artistArtwork.FileName!);
// Every owner of the artwork is removed from the innermost children outwards, so that no artwork is orphaned.
Received.InOrder(() =>
{
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, firstAlbumId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, thirdTrackId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, secondAlbumId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>());
});
}
[Fact]
public async Task DeleteArtistArtworkAsync_WhenGetAlbumsFails_ShouldReturnTheErrorWithoutDeletingAnyArtwork()
{
// Arrange
Guid artistId = Guid.NewGuid();
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.DeleteArtistArtworkAsync(artistId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any<string>());
}
[Fact]
public async Task DeleteArtistArtworkAsync_WhenAChildArtworkCleanupFails_ShouldReturnTheErrorWithoutDeletingTheArtistArtwork()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false);
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.DeleteArtistArtworkAsync(artistId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteAlbumArtworkAsync_WhenAlbumHasTracks_ShouldRemoveTheArtworkOfTheTracksBeforeTheAlbumArtwork()
{
// Arrange
Guid albumId = Guid.NewGuid();
Guid firstTrackId = Guid.NewGuid();
Guid secondTrackId = Guid.NewGuid();
TrackEntity firstTrack = _trackEntityFixture.Create(id: firstTrackId, albumId: albumId);
TrackEntity secondTrack = _trackEntityFixture.Create(id: secondTrackId, albumId: albumId);
MusicArtworkEntity firstTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: firstTrackId, fileName: "/media/music/first-track.jpg");
MusicArtworkEntity secondTrackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: secondTrackId, fileName: "/media/music/second-track.jpg");
MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, fileName: "/media/music/album.jpg");
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([firstTrack, secondTrack]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([firstTrackArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([secondTrackArtwork]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([albumArtwork]));
// Act
Result<Deleted> result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(firstTrackArtwork.FileName!);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(secondTrackArtwork.FileName!);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(albumArtwork.FileName!);
Received.InOrder(() =>
{
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, firstTrackId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, secondTrackId, Arg.Any<CancellationToken>());
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>());
});
}
[Fact]
public async Task DeleteAlbumArtworkAsync_WhenGetTracksFails_ShouldReturnTheErrorWithoutDeletingAnyArtwork()
{
// Arrange
Guid albumId = Guid.NewGuid();
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteAlbumArtworkAsync_WhenGetArtworkFails_ShouldReturnTheErrorWithoutDeletingTheRecords()
{
// Arrange
Guid albumId = Guid.NewGuid();
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteAlbumArtworkAsync_WhenDeletingTheArtworkRecordsFails_ShouldReturnTheError()
{
// Arrange
Guid albumId = Guid.NewGuid();
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
}
[Fact]
public async Task DeleteAlbumArtworkAsync_WhenDeletingAStoredArtworkFileFails_ShouldReturnTheErrorWithoutDeletingTheRecords()
{
// Arrange
Guid albumId = Guid.NewGuid();
MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, fileName: "/media/music/album.jpg");
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([albumArtwork]));
_mockMusicArtworkService.DeleteStoredArtwork(albumArtwork.FileName!)
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteAlbumArtworkAsync_WhenArtworkHasNoStoredFile_ShouldSkipTheFileDeletionButDeleteTheRecords()
{
// Arrange
Guid albumId = Guid.NewGuid();
// An artwork whose file has not been resolved yet has no file to remove, but its record still has to be removed.
MusicArtworkEntity unresolvedArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, includeFileName: false);
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([unresolvedArtwork]));
// Act
Result<Deleted> result = await _sut.DeleteAlbumArtworkAsync(albumId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any<string>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteTrackArtworkAsync_WhenArtworkExists_ShouldDeleteTheStoredFilesAndTheRecords()
{
// Arrange
Guid trackId = Guid.NewGuid();
MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: trackId, fileName: "/media/music/track.jpg");
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([trackArtwork]));
// Act
Result<Deleted> result = await _sut.DeleteTrackArtworkAsync(trackId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(trackArtwork.FileName!);
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteTrackArtworkAsync_WhenNoArtworkExists_ShouldStillDeleteTheRecords()
{
// Arrange
Guid trackId = Guid.NewGuid();
// Act
Result<Deleted> result = await _sut.DeleteTrackArtworkAsync(trackId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockMusicArtworkService.DidNotReceive().DeleteStoredArtwork(Arg.Any<string>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, trackId, Arg.Any<CancellationToken>());
}
}
@@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
@@ -33,6 +34,7 @@ public class DeleteTrackCommandHandlerTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<DeleteTrackCommand> _mockValidator;
@@ -54,22 +56,25 @@ public class DeleteTrackCommandHandlerTests
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockMusicArtworkCleanupService = Substitute.For<IMusicArtworkCleanupService>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<DeleteTrackCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist update succeeds and saving changes succeeds.
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist update succeeds, the artwork cleanup succeeds and saving changes succeeds.
_mockValidator.Validate(Arg.Any<DeleteTrackCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new DeleteTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
_sut = new DeleteTrackCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
@@ -87,6 +92,13 @@ public class DeleteTrackCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
// The artwork of the track is removed before the track is removed from the artist aggregate, so that no artwork is orphaned.
await _mockMusicArtworkCleanupService.Received(1).DeleteTrackArtworkAsync(trackId, Arg.Any<CancellationToken>());
Received.InOrder(() =>
{
_mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, Arg.Any<CancellationToken>());
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
});
await _mockArtistRepository.Received(1).UpdateAsync(
Arg.Is<ArtistEntity>(updatedArtist =>
updatedArtist.Id == artistId &&
@@ -141,6 +153,7 @@ public class DeleteTrackCommandHandlerTests
Assert.Equal(DomainErrors.Music.TrackIdCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkCleanupService.DidNotReceive().DeleteTrackArtworkAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -360,6 +373,28 @@ public class DeleteTrackCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutUpdatingTheArtist()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
StubArtistAndLibrary(artist, libraryId);
Error error = Error.Failure(description: "Failed to delete the artwork");
_mockMusicArtworkCleanupService.DeleteTrackArtworkAsync(trackId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving()
{
@@ -1,4 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Core.MediaLibrary.Management.Events;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
@@ -17,6 +20,7 @@ using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events;
@@ -27,6 +31,11 @@ namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events;
[ExcludeFromCodeCoverage]
public class LibraryDeletedDomainEventHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly IArtistRepository _mockArtistRepository;
private readonly IBookRepository _mockBookRepository;
private readonly IMusicLibraryScanItemMetadataRepository _mockMusicLibraryScanItemMetadataRepository;
private readonly IEnvironmentContext _mockEnvironmentContext;
private readonly IDirectoryProviderService _mockDirectoryProviderService;
private readonly IPathService _mockPathService;
@@ -40,6 +49,20 @@ public class LibraryDeletedDomainEventHandlerTests
/// </summary>
public LibraryDeletedDomainEventHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockMusicLibraryScanItemMetadataRepository = Substitute.For<IMusicLibraryScanItemMetadataRepository>();
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicLibraryScanItemMetadataRepository);
_mockMusicArtworkRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockArtistRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockBookRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockMusicLibraryScanItemMetadataRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
@@ -48,20 +71,24 @@ public class LibraryDeletedDomainEventHandlerTests
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(
rootDirectory: "Media",
librariesDirectory: "Libraries",
booksDirectory: "Books");
booksDirectory: "Books",
musicDirectory: "Music");
IOptions<MediaSettingsDto> mediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
mediaSettingsOptions.Value.Returns(mediaSettings);
// default stubs: all path combinations succeed and the directory is deleted successfully
// default stubs: all path combinations succeed, segments are sanitized to their input, the library directories exist and they are deleted successfully
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(string.Concat(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo => PathSegment.Create(callInfo.ArgAt<string>(0), isDirectory: false, isDrive: false));
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockDirectoryProviderService.DeleteDirectory(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
_sut = new LibraryDeletedDomainEventHandler(_mockEnvironmentContext, _mockPathService, mediaSettingsOptions);
_sut = new LibraryDeletedDomainEventHandler(_mockUnitOfWork, _mockEnvironmentContext, _mockPathService, mediaSettingsOptions);
}
[Fact]
public async Task HandleAsync_WhenLibraryIsDeleted_ShouldDeleteLibraryDirectory()
public async Task HandleAsync_WhenLibraryIsDeleted_ShouldDeleteMediaItemsAndLibraryDirectory()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -72,7 +99,11 @@ public class LibraryDeletedDomainEventHandlerTests
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
_mockDirectoryProviderService.Received(1).DeleteDirectory(
await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
_mockDirectoryProviderService.Received(3).DeleteDirectory(
Arg.Is<FileSystemPathId>(path => path.Path.EndsWith(libraryId.ToString(), StringComparison.Ordinal)));
}
@@ -112,4 +143,243 @@ public class LibraryDeletedDomainEventHandlerTests
Assert.Equal(error, exception.EventualConsistencyError);
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[Fact]
public async Task HandleAsync_WhenDeleteMusicArtworkFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingAnythingElse()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to delete music artwork");
_mockMusicArtworkRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockArtistRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[Fact]
public async Task HandleAsync_WhenDeleteArtistsFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingAnythingElse()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to delete artists");
_mockArtistRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
// The artwork is deleted before its owners, so that its owners are still present when the artwork is looked up.
await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[Fact]
public async Task HandleAsync_WhenDeleteBooksFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingAnythingElse()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to delete books");
_mockBookRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[Fact]
public async Task HandleAsync_WhenDeleteStagedMusicMetadataFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingAnythingElse()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to delete staged music metadata");
_mockMusicLibraryScanItemMetadataRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[Fact]
public async Task HandleAsync_WhenSanitizeSegmentFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingItemDirectories()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to sanitize segment");
_mockPathService.SanitizeSegment(Arg.Any<string>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
// Only the libraries directory, deleted before the segment is sanitized, was removed.
_mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[Fact]
public async Task HandleAsync_WhenLibraryIsDeleted_ShouldDeleteEachMediaTypeDirectoryAtItsExactPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
string libraryTitle = "My Library";
Library library = _libraryFixture.Create(id: libraryId, title: libraryTitle);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
string librarySegment = $"{libraryTitle}-{libraryId}";
string expectedLibrariesPath = string.Concat(AppContext.BaseDirectory, "Media", "Libraries", libraryId.ToString());
string expectedBooksPath = string.Concat(AppContext.BaseDirectory, "Media", "Books", librarySegment);
string expectedMusicPath = string.Concat(AppContext.BaseDirectory, "Media", "Music", librarySegment);
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
_mockPathService.Received(1).SanitizeSegment(librarySegment);
_mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is<FileSystemPathId>(path => path.Path == expectedLibrariesPath));
_mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is<FileSystemPathId>(path => path.Path == expectedBooksPath));
_mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Is<FileSystemPathId>(path => path.Path == expectedMusicPath));
}
[Fact]
public async Task HandleAsync_WhenLibraryDirectoryDoesNotExist_ShouldSkipDeletingIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
// Act
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
// The media items are still removed, but a directory that does not exist is not an error.
await _mockMusicArtworkRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockMusicLibraryScanItemMetadataRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[Fact]
public async Task HandleAsync_WhenDirectoryExistsFails_ShouldThrowEventualConsistencyException()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to check directory existence");
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[Fact]
public async Task HandleAsync_WhenCombiningTheMediaTypeDirectoryPathFails_ShouldThrowEventualConsistencyException()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, title: "My Library");
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
Error error = Error.Failure(description: "Failed to combine the media type directory path");
// Only the combination of the media type segment of the books directory fails, after the libraries directory was already removed.
_mockPathService.CombinePath(Arg.Any<string>(), "Books").Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
// Only the libraries directory, whose path was combined before the failure, was removed.
_mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[Fact]
public async Task HandleAsync_WhenCombiningTheLibraryDirectoryPathFails_ShouldThrowEventualConsistencyException()
{
// Arrange
Guid libraryId = Guid.NewGuid();
string libraryTitle = "My Library";
Library library = _libraryFixture.Create(id: libraryId, title: libraryTitle);
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
string librarySegment = $"{libraryTitle}-{libraryId}";
Error error = Error.Failure(description: "Failed to combine the library directory path");
// Only the combination of the leaf library segment of the books directory fails.
_mockPathService.CombinePath(Arg.Is<string>(path => path.EndsWith("Books", StringComparison.Ordinal)), librarySegment).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(error, exception.EventualConsistencyError);
// Only the libraries directory, whose path was combined before the failure, was removed.
_mockDirectoryProviderService.Received(1).DeleteDirectory(Arg.Any<FileSystemPathId>());
}
[Fact]
public async Task HandleAsync_WhenCreatingTheLibraryPathIdFails_ShouldThrowEventualConsistencyException()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Library library = _libraryFixture.Create(id: libraryId, title: "My Library");
LibraryDeletedDomainEvent domainEvent = _libraryDeletedDomainEventFixture.Create(library: library);
// The combined leaf path of the libraries directory is blank, so the path value object cannot be created from it.
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Is(libraryId.ToString())).Returns(Result.From(" "));
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, exception.EventualConsistencyError);
_mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any<FileSystemPathId>());
}
}