Adds deletion and restore for music library items.

This commit is contained in:
BinaryAlley committed 2026-11-15 18:53:10 +02:00
1 parent 98515dc5e8
commit f9ad8b2fc5
224 files changed
+22384 -1360

No files matched your search

@@ -55,10 +55,12 @@ public class AlbumEntityFixture
/// <param name="releaseStatus">Optional. The release status of the album.</param>
/// <param name="totalDiscs">Optional. The total number of discs of the album.</param>
/// <param name="mediaFormat">Optional. The media format of the album.</param>
/// <param name="catalogNumber">Optional. The catalog number of the album.</param>
/// <param name="catalogNumbers">Optional. The catalog numbers of the album.</param>
/// <param name="musicBrainzReleaseId">Optional. The MusicBrainz release identifier of the album.</param>
/// <param name="musicBrainzReleaseGroupId">Optional. The MusicBrainz release group identifier of the album.</param>
/// <param name="musicBrainzReleaseArtistId">Optional. The MusicBrainz release artist identifier of the album.</param>
/// <param name="isDeleted">Whether the album is soft deleted.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the album was deleted.</param>
/// <param name="includeTracks">Whether the album should own a generated track, or no track at all.</param>
/// <param name="includeMetadata">Whether the owned metadata collections (Tags, Genres, Contributors, Ratings) should be included, or forced to empty collections.</param>
/// <param name="includeOriginalReleaseDate">Whether the original release date should be included, or forced to <see langword="null"/>.</param>
@@ -78,6 +80,7 @@ public class AlbumEntityFixture
/// <param name="includeMusicBrainzReleaseId">Whether the MusicBrainz release identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzReleaseGroupId">Whether the MusicBrainz release group identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzReleaseArtistId">Whether the MusicBrainz release artist identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeletedOnUtc">Whether a deleted album should carry a deletion time, or <see langword="null"/>.</param>
/// <param name="metadataStatus">Optional. The metadata enrichment status of the album.</param>
/// <returns>The created <see cref="AlbumEntity"/>.</returns>
public AlbumEntity Create(
@@ -107,6 +110,8 @@ public class AlbumEntityFixture
Guid? musicBrainzReleaseId = null,
Guid? musicBrainzReleaseGroupId = null,
Guid? musicBrainzReleaseArtistId = null,
bool isDeleted = false,
DateTime? deletedOnUtc = null,
bool includeTracks = true,
bool includeMetadata = true,
bool includeOriginalReleaseDate = true,
@@ -126,6 +131,7 @@ public class AlbumEntityFixture
bool includeMusicBrainzReleaseId = true,
bool includeMusicBrainzReleaseGroupId = true,
bool includeMusicBrainzReleaseArtistId = true,
bool includeDeletedOnUtc = true,
MetadataStatus? metadataStatus = null)
{
Guid resolvedId = id ?? Guid.NewGuid();
@@ -182,6 +188,8 @@ public class AlbumEntityFixture
.RuleFor(x => x.Contributors, f => includeMetadata ? _albumContributorEntityFixture.CreateMany(f.Random.Number(1, 3), albumId: resolvedId) : [])
.RuleFor(x => x.Ratings, f => includeMetadata ? _audioRatingEntityFixture.CreateMany(f.Random.Number(1, 3)) : [])
.RuleFor(x => x.Tracks, resolvedTracks)
.RuleFor(x => x.IsDeleted, isDeleted)
.RuleFor(x => x.DeletedOnUtc, f => isDeleted && includeDeletedOnUtc ? (deletedOnUtc ?? f.Date.Recent()) : null)
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
.RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent())
.Generate();
@@ -27,11 +27,14 @@ public class ArtistEntityFixture
/// <param name="website">Optional. The website of the artist.</param>
/// <param name="musicBrainzArtistId">Optional. The MusicBrainz identifier of the artist.</param>
/// <param name="albums">Optional. The albums of the artist.</param>
/// <param name="isDeleted">Whether the artist is soft deleted.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the artist was deleted.</param>
/// <param name="includeAlbums">Whether the artist should own a generated album, or no album at all.</param>
/// <param name="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeContributors">Whether the artist should own a generated media contributor, or none at all.</param>
/// <param name="includeMetadata">Whether the owned metadata collections of the generated album should be included, or forced to empty collections.</param>
/// <param name="includeDeletedOnUtc">Whether a deleted artist should carry a deletion time, or <see langword="null"/>.</param>
/// <returns>The created <see cref="ArtistEntity"/>.</returns>
public ArtistEntity Create(
Guid? id = null,
@@ -40,11 +43,14 @@ public class ArtistEntityFixture
string? website = null,
Guid? musicBrainzArtistId = null,
List<AlbumEntity>? albums = null,
bool isDeleted = false,
DateTime? deletedOnUtc = null,
bool includeAlbums = true,
bool includeWebsite = true,
bool includeMusicBrainzArtistId = true,
bool includeContributors = true,
bool includeMetadata = true)
bool includeMetadata = true,
bool includeDeletedOnUtc = true)
{
Guid resolvedId = id ?? Guid.NewGuid();
Guid resolvedLibraryId = libraryId ?? Guid.NewGuid();
@@ -65,6 +71,8 @@ public class ArtistEntityFixture
.RuleFor(x => x.MusicBrainzArtistId, f => includeMusicBrainzArtistId ? (musicBrainzArtistId ?? f.Random.Guid()) : null)
.RuleFor(x => x.Albums, resolvedAlbums)
.RuleFor(x => x.Contributors, f => includeContributors ? _artistContributorEntityFixture.CreateMany(f.Random.Number(1, 3), artistId: resolvedId) : [])
.RuleFor(x => x.IsDeleted, isDeleted)
.RuleFor(x => x.DeletedOnUtc, f => isDeleted && includeDeletedOnUtc ? (deletedOnUtc ?? f.Date.Recent()) : null)
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
.RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent())
.Generate();
@@ -44,6 +44,8 @@ public class TrackEntityFixture
/// <param name="originalReleaseYear">Optional. The original release year of the track.</param>
/// <param name="reReleaseDate">Optional. The re-release date of the track.</param>
/// <param name="reReleaseYear">Optional. The re-release year of the track.</param>
/// <param name="isDeleted">Whether the track is soft deleted.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the track was deleted.</param>
/// <param name="includeMetadata">Whether the owned metadata collections (Tags, Genres, Moods, ISRCs, Contributors, Ratings) should be included, or forced to empty collections.</param>
/// <param name="includeOriginalReleaseDate">Whether the original release date should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeOriginalReleaseYear">Whether the original release year should be included, or forced to <see langword="null"/>.</param>
@@ -58,6 +60,7 @@ public class TrackEntityFixture
/// <param name="replayGainAlbumGain">Optional. The ReplayGain album gain of the track, in decibels.</param>
/// <param name="replayGainAlbumPeak">Optional. The ReplayGain album peak of the track.</param>
/// <param name="includeReplayGain">Whether the ReplayGain values should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDeletedOnUtc">Whether a deleted track should carry a deletion time, or <see langword="null"/>.</param>
/// <returns>The created <see cref="TrackEntity"/>.</returns>
public TrackEntity Create(
Guid? id = null,
@@ -72,6 +75,8 @@ public class TrackEntityFixture
int? originalReleaseYear = null,
DateOnly? reReleaseDate = null,
int? reReleaseYear = null,
bool isDeleted = false,
DateTime? deletedOnUtc = null,
bool includeMetadata = true,
bool includeOriginalReleaseDate = true,
bool includeOriginalReleaseYear = true,
@@ -85,7 +90,8 @@ public class TrackEntityFixture
decimal? replayGainTrackPeak = null,
decimal? replayGainAlbumGain = null,
decimal? replayGainAlbumPeak = null,
bool includeReplayGain = true)
bool includeReplayGain = true,
bool includeDeletedOnUtc = true)
{
Guid resolvedId = id ?? Guid.NewGuid();
Guid resolvedAlbumId = albumId ?? Guid.NewGuid();
@@ -154,6 +160,8 @@ public class TrackEntityFixture
.RuleFor(x => x.Isrcs, f => includeMetadata ? _trackIsrcEntityFixture.CreateMany(f.Random.Number(1, 3)) : [])
.RuleFor(x => x.Contributors, f => includeMetadata ? _trackContributorEntityFixture.CreateMany(f.Random.Number(1, 3), trackId: resolvedId) : [])
.RuleFor(x => x.Ratings, f => includeMetadata ? _audioRatingEntityFixture.CreateMany(f.Random.Number(1, 3)) : [])
.RuleFor(x => x.IsDeleted, isDeleted)
.RuleFor(x => x.DeletedOnUtc, f => isDeleted && includeDeletedOnUtc ? (deletedOnUtc ?? f.Date.Recent()) : null)
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
.RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent())
.Generate();
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
/// <summary>
/// Fixture class for the <see cref="RestoreAlbumCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreAlbumCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="RestoreAlbumCommand"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the album belongs to, taken from the route.</param>
/// <param name="artistId">Optional. The Id of the artist the album belongs to, taken from the route.</param>
/// <param name="albumId">Optional. The Id of the deleted album to restore, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="RestoreAlbumCommand"/>.</returns>
public RestoreAlbumCommand Create(
string? libraryId = null,
string? artistId = null,
string? albumId = null,
bool includeLibraryId = true,
bool includeArtistId = true,
bool includeAlbumId = true)
{
return new RestoreAlbumCommand(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null);
}
/// <summary>
/// Creates a list of <see cref="RestoreAlbumCommand"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="RestoreAlbumCommand"/> instances.</returns>
public List<RestoreAlbumCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
/// <summary>
/// Fixture class for the <see cref="GetDeletedAlbumsQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedAlbumsQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetDeletedAlbumsQuery"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose deleted albums are retrieved, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetDeletedAlbumsQuery"/>.</returns>
public GetDeletedAlbumsQuery Create(
string? libraryId = null,
bool includeLibraryId = true)
{
return new GetDeletedAlbumsQuery(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null);
}
/// <summary>
/// Creates a list of <see cref="GetDeletedAlbumsQuery"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetDeletedAlbumsQuery"/> instances.</returns>
public List<GetDeletedAlbumsQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,45 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
/// <summary>
/// Fixture class for the <see cref="RestoreArtistCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreArtistCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="RestoreArtistCommand"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the artist belongs to, taken from the route.</param>
/// <param name="artistId">Optional. The Id of the deleted artist to restore, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="RestoreArtistCommand"/>.</returns>
public RestoreArtistCommand Create(
string? libraryId = null,
string? artistId = null,
bool includeLibraryId = true,
bool includeArtistId = true)
{
return new RestoreArtistCommand(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null);
}
/// <summary>
/// Creates a list of <see cref="RestoreArtistCommand"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="RestoreArtistCommand"/> instances.</returns>
public List<RestoreArtistCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
/// <summary>
/// Fixture class for the <see cref="GetDeletedArtistsQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedArtistsQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetDeletedArtistsQuery"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose deleted artists are retrieved, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetDeletedArtistsQuery"/>.</returns>
public GetDeletedArtistsQuery Create(
string? libraryId = null,
bool includeLibraryId = true)
{
return new GetDeletedArtistsQuery(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null);
}
/// <summary>
/// Creates a list of <see cref="GetDeletedArtistsQuery"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetDeletedArtistsQuery"/> instances.</returns>
public List<GetDeletedArtistsQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
/// <summary>
/// Fixture class for the <see cref="RestoreTrackCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreTrackCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="RestoreTrackCommand"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the track belongs to, taken from the route.</param>
/// <param name="artistId">Optional. The Id of the artist the album of the track belongs to, taken from the route.</param>
/// <param name="albumId">Optional. The Id of the album the track belongs to, taken from the route.</param>
/// <param name="trackId">Optional. The Id of the deleted track to restore, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="RestoreTrackCommand"/>.</returns>
public RestoreTrackCommand Create(
string? libraryId = null,
string? artistId = null,
string? albumId = null,
string? trackId = null,
bool includeLibraryId = true,
bool includeArtistId = true,
bool includeAlbumId = true,
bool includeTrackId = true)
{
return new RestoreTrackCommand(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null);
}
/// <summary>
/// Creates a list of <see cref="RestoreTrackCommand"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="RestoreTrackCommand"/> instances.</returns>
public List<RestoreTrackCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
/// <summary>
/// Fixture class for the <see cref="GetDeletedTracksQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedTracksQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetDeletedTracksQuery"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library whose deleted tracks are retrieved, taken from the route.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetDeletedTracksQuery"/>.</returns>
public GetDeletedTracksQuery Create(
string? libraryId = null,
bool includeLibraryId = true)
{
return new GetDeletedTracksQuery(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null);
}
/// <summary>
/// Creates a list of <see cref="GetDeletedTracksQuery"/>.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetDeletedTracksQuery"/> instances.</returns>
public List<GetDeletedTracksQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
/// <summary>
/// Fixture class for the <see cref="DeletedAlbumResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedAlbumResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="DeletedAlbumResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the deleted album.</param>
/// <param name="libraryId">Optional. The Id of the media library the deleted album belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist the deleted album belongs to.</param>
/// <param name="artistName">Optional. The name of the artist the deleted album belongs to.</param>
/// <param name="title">Optional. The title of the deleted album.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the album was deleted.</param>
/// <param name="coverPath">Optional. The path of the cover image of the deleted album.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="DeletedAlbumResponse"/>.</returns>
public DeletedAlbumResponse Create(
Guid? id = null,
Guid? libraryId = null,
Guid? artistId = null,
string? artistName = null,
string? title = null,
DateTime? deletedOnUtc = null,
string? coverPath = null,
bool includeCoverPath = true)
{
return new DeletedAlbumResponse(
id ?? _faker.Random.Guid(),
libraryId ?? _faker.Random.Guid(),
artistId ?? _faker.Random.Guid(),
artistName ?? _faker.Name.FullName(),
title ?? _faker.Music.Genre(),
deletedOnUtc ?? _faker.Date.Recent().ToUniversalTime(),
includeCoverPath ? (coverPath ?? $"/covers/{_faker.Random.Guid()}.jpg") : null);
}
/// <summary>
/// Creates a list of <see cref="DeletedAlbumResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeletedAlbumResponse"/> instances.</returns>
public List<DeletedAlbumResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
/// <summary>
/// Fixture class for the <see cref="DeletedArtistResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedArtistResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="DeletedArtistResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the deleted artist.</param>
/// <param name="libraryId">Optional. The Id of the media library the deleted artist belongs to.</param>
/// <param name="name">Optional. The name of the deleted artist.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the artist was deleted.</param>
/// <param name="coverPath">Optional. The path of the cover image of the deleted artist.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="DeletedArtistResponse"/>.</returns>
public DeletedArtistResponse Create(
Guid? id = null,
Guid? libraryId = null,
string? name = null,
DateTime? deletedOnUtc = null,
string? coverPath = null,
bool includeCoverPath = true)
{
return new DeletedArtistResponse(
id ?? _faker.Random.Guid(),
libraryId ?? _faker.Random.Guid(),
name ?? _faker.Name.FullName(),
deletedOnUtc ?? _faker.Date.Recent().ToUniversalTime(),
includeCoverPath ? (coverPath ?? $"/covers/{_faker.Random.Guid()}.jpg") : null);
}
/// <summary>
/// Creates a list of <see cref="DeletedArtistResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeletedArtistResponse"/> instances.</returns>
public List<DeletedArtistResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,65 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Fixture class for the <see cref="DeletedTrackResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedTrackResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="DeletedTrackResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the deleted track.</param>
/// <param name="libraryId">Optional. The Id of the media library the deleted track belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist the deleted track belongs to.</param>
/// <param name="artistName">Optional. The name of the artist the deleted track belongs to.</param>
/// <param name="albumId">Optional. The Id of the album the deleted track belongs to.</param>
/// <param name="albumTitle">Optional. The title of the album the deleted track belongs to.</param>
/// <param name="title">Optional. The title of the deleted track.</param>
/// <param name="path">Optional. The file system path of the deleted track.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the track was deleted.</param>
/// <returns>The created <see cref="DeletedTrackResponse"/>.</returns>
public DeletedTrackResponse Create(
Guid? id = null,
Guid? libraryId = null,
Guid? artistId = null,
string? artistName = null,
Guid? albumId = null,
string? albumTitle = null,
string? title = null,
string? path = null,
DateTime? deletedOnUtc = null)
{
return new DeletedTrackResponse(
id ?? _faker.Random.Guid(),
libraryId ?? _faker.Random.Guid(),
artistId ?? _faker.Random.Guid(),
artistName ?? _faker.Name.FullName(),
albumId ?? _faker.Random.Guid(),
albumTitle ?? _faker.Music.Genre(),
title ?? _faker.Music.Genre(),
path ?? $"/music/tracks/{_faker.Random.Guid()}.flac",
deletedOnUtc ?? _faker.Date.Recent().ToUniversalTime());
}
/// <summary>
/// Creates a list of <see cref="DeletedTrackResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeletedTrackResponse"/> instances.</returns>
public List<DeletedTrackResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="DeletedMusicAlbumDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedMusicAlbumDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="DeletedMusicAlbumDto"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The Id of the deleted album.</param>
/// <param name="libraryId">Optional. The Id of the media library the deleted album belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist the deleted album belongs to.</param>
/// <param name="artistName">Optional. The name of the artist the deleted album belongs to.</param>
/// <param name="title">Optional. The title of the deleted album.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the album was deleted.</param>
/// <param name="coverPath">Optional. The relative path of the stored cover image of the deleted album.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="DeletedMusicAlbumDto"/>.</returns>
public DeletedMusicAlbumDto Create(
Guid? id = null,
Guid? libraryId = null,
Guid? artistId = null,
string? artistName = null,
string? title = null,
DateTime? deletedOnUtc = null,
string? coverPath = null,
bool includeCoverPath = true)
{
return new DeletedMusicAlbumDto(
Id: id ?? _faker.Random.Guid(),
LibraryId: libraryId ?? _faker.Random.Guid(),
ArtistId: artistId ?? _faker.Random.Guid(),
ArtistName: artistName ?? _faker.Lorem.Word(),
Title: title ?? _faker.Lorem.Sentence(),
DeletedOnUtc: deletedOnUtc ?? _faker.Date.Recent(),
CoverPath: includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null
);
}
/// <summary>
/// Creates multiple <see cref="DeletedMusicAlbumDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeletedMusicAlbumDto"/> instances.</returns>
public List<DeletedMusicAlbumDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="DeletedMusicArtistDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedMusicArtistDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="DeletedMusicArtistDto"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The Id of the deleted artist.</param>
/// <param name="libraryId">Optional. The Id of the media library the deleted artist belongs to.</param>
/// <param name="name">Optional. The name of the deleted artist.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the artist was deleted.</param>
/// <param name="coverPath">Optional. The relative path of the stored cover image of the deleted artist.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="DeletedMusicArtistDto"/>.</returns>
public DeletedMusicArtistDto Create(
Guid? id = null,
Guid? libraryId = null,
string? name = null,
DateTime? deletedOnUtc = null,
string? coverPath = null,
bool includeCoverPath = true)
{
return new DeletedMusicArtistDto(
Id: id ?? _faker.Random.Guid(),
LibraryId: libraryId ?? _faker.Random.Guid(),
Name: name ?? _faker.Lorem.Word(),
DeletedOnUtc: deletedOnUtc ?? _faker.Date.Recent(),
CoverPath: includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null
);
}
/// <summary>
/// Creates multiple <see cref="DeletedMusicArtistDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeletedMusicArtistDto"/> instances.</returns>
public List<DeletedMusicArtistDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="DeletedMusicItemsPageDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedMusicItemsPageDtoFixture
{
private readonly Faker _faker = new();
private readonly LibraryDtoFixture _libraryDtoFixture = new();
private readonly DeletedMusicArtistDtoFixture _deletedMusicArtistDtoFixture = new();
private readonly DeletedMusicAlbumDtoFixture _deletedMusicAlbumDtoFixture = new();
private readonly DeletedMusicTrackDtoFixture _deletedMusicTrackDtoFixture = new();
/// <summary>
/// Creates a new <see cref="DeletedMusicItemsPageDto"/> instance with randomized test data.
/// </summary>
/// <param name="library">Optional. The media library whose deleted music items are shown.</param>
/// <param name="deletedArtists">Optional. The deleted artists of the media library.</param>
/// <param name="deletedAlbums">Optional. The deleted albums of the media library.</param>
/// <param name="deletedTracks">Optional. The deleted tracks of the media library.</param>
/// <returns>The created <see cref="DeletedMusicItemsPageDto"/>.</returns>
public DeletedMusicItemsPageDto Create(
LibraryDto? library = null,
IReadOnlyList<DeletedMusicArtistDto>? deletedArtists = null,
IReadOnlyList<DeletedMusicAlbumDto>? deletedAlbums = null,
IReadOnlyList<DeletedMusicTrackDto>? deletedTracks = null)
{
return new DeletedMusicItemsPageDto(
Library: library ?? _libraryDtoFixture.Create(),
DeletedArtists: deletedArtists ?? _deletedMusicArtistDtoFixture.CreateMany(_faker.Random.Number(1, 3)),
DeletedAlbums: deletedAlbums ?? _deletedMusicAlbumDtoFixture.CreateMany(_faker.Random.Number(1, 3)),
DeletedTracks: deletedTracks ?? _deletedMusicTrackDtoFixture.CreateMany(_faker.Random.Number(1, 3))
);
}
/// <summary>
/// Creates multiple <see cref="DeletedMusicItemsPageDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeletedMusicItemsPageDto"/> instances.</returns>
public List<DeletedMusicItemsPageDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
/// <summary>
/// Fixture class for the <see cref="DeletedMusicTrackDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedMusicTrackDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="DeletedMusicTrackDto"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The Id of the deleted track.</param>
/// <param name="libraryId">Optional. The Id of the media library the deleted track belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist the deleted track belongs to.</param>
/// <param name="artistName">Optional. The name of the artist the deleted track belongs to.</param>
/// <param name="albumId">Optional. The Id of the album the deleted track belongs to.</param>
/// <param name="albumTitle">Optional. The title of the album the deleted track belongs to.</param>
/// <param name="title">Optional. The title of the deleted track.</param>
/// <param name="path">Optional. The file system path of the deleted track.</param>
/// <param name="deletedOnUtc">Optional. The date and time when the track was deleted.</param>
/// <returns>The created <see cref="DeletedMusicTrackDto"/>.</returns>
public DeletedMusicTrackDto Create(
Guid? id = null,
Guid? libraryId = null,
Guid? artistId = null,
string? artistName = null,
Guid? albumId = null,
string? albumTitle = null,
string? title = null,
string? path = null,
DateTime? deletedOnUtc = null)
{
return new DeletedMusicTrackDto(
Id: id ?? _faker.Random.Guid(),
LibraryId: libraryId ?? _faker.Random.Guid(),
ArtistId: artistId ?? _faker.Random.Guid(),
ArtistName: artistName ?? _faker.Lorem.Word(),
AlbumId: albumId ?? _faker.Random.Guid(),
AlbumTitle: albumTitle ?? _faker.Lorem.Sentence(),
Title: title ?? _faker.Lorem.Sentence(),
Path: path ?? _faker.System.FilePath(),
DeletedOnUtc: deletedOnUtc ?? _faker.Date.Recent()
);
}
/// <summary>
/// Creates multiple <see cref="DeletedMusicTrackDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeletedMusicTrackDto"/> instances.</returns>
public List<DeletedMusicTrackDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -52,6 +52,7 @@ public class FavoriteRepositoryTests
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly DateTime _deletedOnUtc = new(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc);
[Fact]
public async Task InsertAsync_WhenTheFavoriteIsNew_ShouldReturnCreatedAndPersistEveryField()
@@ -1119,6 +1120,59 @@ public class FavoriteRepositoryTests
Assert.Empty(result.Value);
}
[Theory]
[InlineData(FavoriteMediaKind.MusicArtist, false)] // the artist itself is soft deleted
[InlineData(FavoriteMediaKind.MusicAlbum, false)] // the album itself is soft deleted
[InlineData(FavoriteMediaKind.MusicAlbum, true)] // the album's artist is soft deleted
[InlineData(FavoriteMediaKind.MusicTrack, false)] // the track itself is soft deleted
[InlineData(FavoriteMediaKind.MusicTrack, true)] // the track's album is soft deleted
public async Task GetMediaItemLibraryIdAsync_WhenTheMusicItemIsSoftDeleted_ShouldReturnSuccessWithNull(FavoriteMediaKind mediaKind, bool isAncestorDeleted)
{
// Arrange
using SqliteConnection anchorConnection = CreateAnchorConnection($"library-id-deleted-music-{(int)mediaKind}-{isAncestorDeleted}");
using LuminaDbContext context = CreateContext(anchorConnection);
FavoriteRepository sut = new(context);
Guid mediaItemId = await SeedSoftDeletedMusicItemAsync(context, mediaKind, isAncestorDeleted);
// Act
Result<Guid?> result = await sut.GetMediaItemLibraryIdAsync(mediaKind, mediaItemId, CancellationToken.None);
// Assert
// A deleted music item, or one hidden by a deleted ancestor, is not part of the catalogue, so adding it to favorites is rejected as if it did not exist.
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Theory]
[InlineData(FavoriteMediaKind.MusicArtist, false)] // the artist itself is soft deleted
[InlineData(FavoriteMediaKind.MusicAlbum, false)] // the album itself is soft deleted
[InlineData(FavoriteMediaKind.MusicAlbum, true)] // the album's artist is soft deleted
[InlineData(FavoriteMediaKind.MusicTrack, false)] // the track itself is soft deleted
[InlineData(FavoriteMediaKind.MusicTrack, true)] // the track's album is soft deleted
public async Task GetAllForUserAsync_WhenTheFavoritedMusicItemIsSoftDeleted_ShouldKeepTheFavoriteWithoutDisplayData(FavoriteMediaKind mediaKind, bool isAncestorDeleted)
{
// Arrange
using SqliteConnection anchorConnection = CreateAnchorConnection($"list-deleted-music-{(int)mediaKind}-{isAncestorDeleted}");
using LuminaDbContext context = CreateContext(anchorConnection);
FavoriteRepository sut = new(context);
Guid userId = Guid.NewGuid();
context.Users.Add(_userEntityFixture.Create(id: userId));
Guid mediaItemId = await SeedSoftDeletedMusicItemAsync(context, mediaKind, isAncestorDeleted);
FavoriteEntity favorite = CreateFavorite(userId, mediaKind, mediaItemId);
context.Favorites.Add(favorite);
await context.SaveChangesAsync();
// Act
Result<PaginatedResultDto<FavoriteItemDto>> result = await sut.GetAllForUserAsync(userId, mediaKind, paginationData: null, cancellationToken: CancellationToken.None);
// Assert
// A deleted item is hidden from the catalogue, so its favorite must fall back to the unavailable state instead of exposing its display data.
Assert.False(result.IsFailure);
FavoriteItemDto item = Assert.Single(result.Value.Data);
Assert.Equal(favorite.Id, item.Favorite.Id);
Assert.Null(item.Display);
}
/// <summary>
/// Creates an open in-memory SQLite anchor connection with a database name unique to the test.
/// </summary>
@@ -1193,6 +1247,66 @@ public class FavoriteRepositoryTests
includeUpdatedBy: false);
}
/// <summary>
/// Seeds an artist, an album of that artist and a track of that album, and soft deletes the requested music item or one of its ancestors.
/// </summary>
/// <param name="context">The context the catalogue is persisted through.</param>
/// <param name="mediaKind">The kind of the media item that must be hidden from the catalogue.</param>
/// <param name="isAncestorDeleted">Whether an ancestor of the item is soft deleted instead of the item itself.</param>
/// <returns>The Id of the hidden media item.</returns>
private async Task<Guid> SeedSoftDeletedMusicItemAsync(LuminaDbContext context, FavoriteMediaKind mediaKind, bool isAncestorDeleted)
{
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
context.Artists.Add(artist);
await context.SaveChangesAsync();
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
context.Albums.Add(album);
await context.SaveChangesAsync();
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
context.Tracks.Add(track);
await context.SaveChangesAsync();
switch (mediaKind)
{
case FavoriteMediaKind.MusicArtist:
artist.IsDeleted = true;
artist.DeletedOnUtc = _deletedOnUtc;
await context.SaveChangesAsync();
return artist.Id;
case FavoriteMediaKind.MusicAlbum:
if (isAncestorDeleted)
{
artist.IsDeleted = true;
artist.DeletedOnUtc = _deletedOnUtc;
}
else
{
album.IsDeleted = true;
album.DeletedOnUtc = _deletedOnUtc;
}
await context.SaveChangesAsync();
return album.Id;
case FavoriteMediaKind.MusicTrack:
if (isAncestorDeleted)
{
album.IsDeleted = true;
album.DeletedOnUtc = _deletedOnUtc;
}
else
{
track.IsDeleted = true;
track.DeletedOnUtc = _deletedOnUtc;
}
await context.SaveChangesAsync();
return track.Id;
default:
throw new ArgumentOutOfRangeException(nameof(mediaKind), mediaKind, "The fixture only hides music items.");
}
}
/// <summary>
/// Seeds one artist, one album of that artist, one track of that album and one book, each in its own library.
/// </summary>
@@ -47,6 +47,16 @@ public class AlbumRepositoryTests
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
private readonly IDateTimeProvider _mockDateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="AlbumRepositoryTests"/> class.
/// </summary>
public AlbumRepositoryTests()
{
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc));
}
[Fact]
public async Task InsertAsync_WhenCalledWithAValidAlbum_ShouldPersistTheAlbumAndItsAggregate()
@@ -709,14 +719,482 @@ public class AlbumRepositoryTests
Assert.Equal("covers/opera.jpg", row.CoverPath);
}
[Fact]
public async Task GetByIdAsync_WhenTheAlbumIsSoftDeleted_ShouldReturnNull()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Deleted Album");
album.IsDeleted = true;
album.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByIdAsync_WhenItsArtistIsSoftDeleted_ShouldReturnNull()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-deleted-artist-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album Of Deleted Artist");
artist.IsDeleted = true;
artist.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByIdAsync_WhenATrackIsSoftDeleted_ShouldExcludeItFromTheGraph()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-deleted-track-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = BuildFullAlbum(artist.Id, libraryId, "Album");
TrackEntity activeTrack = album.Tracks[0];
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
album.Tracks = [activeTrack, deletedTrack];
context.Albums.Add(album);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
Result<AlbumEntity?> result = await sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeTrack.Id, Assert.Single(result.Value!.Tracks).Id);
}
[Fact]
public async Task GetByArtistIdAsync_WhenAnAlbumIsSoftDeleted_ShouldExcludeIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyartist-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity activeAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Active Album");
AlbumEntity deletedAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Deleted Album");
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<AlbumEntity>> result = await sut.GetByArtistIdAsync(artist.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeAlbum.Id, Assert.Single(result.Value).Id);
}
[Fact]
public async Task GetByArtistIdIncludingDeletedAsync_WhenCalled_ShouldReturnEveryAlbumOfTheArtistOrdered()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyartist-including-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity betaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Beta");
AlbumEntity deletedAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Alpha");
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId);
AlbumEntity albumOfAnotherArtist = await SeedAlbumAsync(context, libraryId, otherArtist.Id, "Gamma");
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<AlbumEntity>> result = await sut.GetByArtistIdIncludingDeletedAsync(artist.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([deletedAlbum.Id, betaAlbum.Id], result.Value.Select(album => album.Id));
Assert.DoesNotContain(result.Value, album => album.Id == albumOfAnotherArtist.Id);
}
[Fact]
public async Task GetIncludingDeletedByIdAsync_WhenTheAlbumIsSoftDeleted_ShouldReturnIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-get-including-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Deleted Album");
album.IsDeleted = true;
album.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await sut.GetIncludingDeletedByIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(album.Id, result.Value!.Id);
Assert.True(result.Value.IsDeleted);
}
[Fact]
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyDeletedAlbumsOfVisibleArtistsOrdered()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getdeleted-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
DateTime deletedOnUtc = _mockDateTimeProvider.UtcNow;
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity olderDeletion = await SeedAlbumAsync(context, libraryId, artist.Id, "Older");
olderDeletion.IsDeleted = true;
olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2);
AlbumEntity newerDeletion = await SeedAlbumAsync(context, libraryId, artist.Id, "Newer");
newerDeletion.IsDeleted = true;
newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1);
AlbumEntity activeAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Active");
ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId);
AlbumEntity deletedAlbumOfDeletedArtist = await SeedAlbumAsync(context, libraryId, deletedArtist.Id, "Hidden");
deletedAlbumOfDeletedArtist.IsDeleted = true;
deletedAlbumOfDeletedArtist.DeletedOnUtc = deletedOnUtc;
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = deletedOnUtc;
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<AlbumEntity>> result = await sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([newerDeletion.Id, olderDeletion.Id], result.Value.Select(album => album.Id));
Assert.DoesNotContain(result.Value, album => album.Id == deletedAlbumOfDeletedArtist.Id);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenAnotherVisibleAlbumOfTheArtistRemains_ShouldPersistTheDeletionStateAndProviderTime()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album");
await SeedAlbumAsync(context, libraryId, artist.Id, "Kept Album");
// Act
Result<Updated> result = await sut.SoftDeleteByIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id);
Assert.True(storedAlbum.IsDeleted);
Assert.Equal(_mockDateTimeProvider.UtcNow, storedAlbum.DeletedOnUtc);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenAlbumIsTheOnlyVisibleAlbumOfTheArtist_ShouldReturnArtistMustHaveAtLeastOneAlbumAndKeepItVisible()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-last-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album");
// Act
Result<Updated> result = await sut.SoftDeleteByIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError);
AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id);
Assert.False(storedAlbum.IsDeleted);
Assert.Null(storedAlbum.DeletedOnUtc);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenTheOtherAlbumsOfTheArtistAreDeleted_ShouldReturnArtistMustHaveAtLeastOneAlbum()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-deleted-siblings-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album");
AlbumEntity deletedAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Deleted Album");
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow.AddHours(-1);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.SoftDeleteByIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError);
AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id);
Assert.False(storedAlbum.IsDeleted);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenAlbumIsAlreadyDeleted_ShouldReturnAlbumNotFound()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-already-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album");
await SeedAlbumAsync(context, libraryId, artist.Id, "Visible Album");
DateTime storedDeletedOnUtc = _mockDateTimeProvider.UtcNow.AddHours(-1);
album.IsDeleted = true;
album.DeletedOnUtc = storedDeletedOnUtc;
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.SoftDeleteByIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id);
Assert.Equal(storedDeletedOnUtc, storedAlbum.DeletedOnUtc);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFound()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-missing-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
// Act
Result<Updated> result = await sut.SoftDeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenAnotherWriterAlreadyDeletedTheOtherLastAlbum_ShouldReturnArtistMustHaveAtLeastOneAlbum()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-softdelete-race-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext firstContext = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
firstContext.Database.EnsureCreated();
using LuminaDbContext secondContext = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
AlbumRepository firstRepository = CreateAlbumRepository(firstContext);
AlbumRepository secondRepository = CreateAlbumRepository(secondContext);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(firstContext, libraryId);
AlbumEntity firstAlbum = await SeedAlbumAsync(firstContext, libraryId, artist.Id, "First Album");
AlbumEntity secondAlbum = await SeedAlbumAsync(firstContext, libraryId, artist.Id, "Second Album");
// The second writer reads the state a preceding check would have seen: both albums visible. The write must not trust that read.
int visibleAlbumsSeenBySecondWriter = await secondContext.Albums.CountAsync(album => album.ArtistId == artist.Id && !album.IsDeleted);
Assert.Equal(2, visibleAlbumsSeenBySecondWriter);
// Act
Result<Updated> firstResult = await firstRepository.SoftDeleteByIdAsync(firstAlbum.Id, CancellationToken.None);
Result<Updated> secondResult = await secondRepository.SoftDeleteByIdAsync(secondAlbum.Id, CancellationToken.None);
// Assert
Assert.False(firstResult.IsFailure);
Assert.True(secondResult.IsFailure);
Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, secondResult.FirstError);
int remainingVisibleAlbums = await secondContext.Albums.CountAsync(album => album.ArtistId == artist.Id && !album.IsDeleted);
Assert.Equal(1, remainingVisibleAlbums);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldPersistTheClearedDeletionState()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-restore-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album");
album.IsDeleted = true;
album.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.RestoreSoftDeletedByIdAsync(album.Id, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id);
Assert.False(storedAlbum.IsDeleted);
Assert.Null(storedAlbum.DeletedOnUtc);
}
[Fact]
public async Task UpdateAsync_WhenTheAlbumIsSoftDeleted_ShouldReturnAlbumNotFound()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album");
album.IsDeleted = true;
album.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
AlbumEntity data = _albumEntityFixture.Create(id: album.Id, artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenItsArtistIsSoftDeleted_ShouldReturnAlbumNotFound()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-deleted-artist-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album");
artist.IsDeleted = true;
artist.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
AlbumEntity data = _albumEntityFixture.Create(id: album.Id, artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenIncomingDataIsMarkedDeleted_ShouldPreserveTheActiveRowsDeletionState()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-preserve-deletion-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
AlbumRepository sut = CreateAlbumRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId);
AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id, "Album");
AlbumEntity data = await LoadDetachedAlbumAsync(context, album.Id);
data.Title = "A Night at the Opera";
data.IsDeleted = true;
data.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == album.Id);
Assert.Equal("A Night at the Opera", storedAlbum.Title);
Assert.False(storedAlbum.IsDeleted);
Assert.Null(storedAlbum.DeletedOnUtc);
}
/// <summary>
/// Creates an album repository backed by the provided context, wiring the real track repository.
/// </summary>
/// <param name="context">The context the repository operates on.</param>
/// <returns>The created repository.</returns>
private static AlbumRepository CreateAlbumRepository(LuminaDbContext context)
private AlbumRepository CreateAlbumRepository(LuminaDbContext context)
{
return new AlbumRepository(context, new TrackRepository(context));
return new AlbumRepository(context, new TrackRepository(context, _mockDateTimeProvider), _mockDateTimeProvider);
}
/// <summary>
@@ -53,6 +53,16 @@ public class ArtistRepositoryTests
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly IDateTimeProvider _mockDateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="ArtistRepositoryTests"/> class.
/// </summary>
public ArtistRepositoryTests()
{
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc));
}
[Fact]
public async Task InsertAsync_WhenCalledWithAValidArtist_ShouldPersistTheArtistAndItsAggregate()
@@ -1332,6 +1342,447 @@ public class ArtistRepositoryTests
Assert.Equal("covers/queen.jpg", row.CoverPath);
}
[Fact]
public async Task InsertAsync_WhenOnlyASoftDeletedArtistHasTheSameName_ShouldPersistTheNewArtist()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-deleted-name-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId, "Queen");
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
// Act
Result<Created> result = await sut.InsertAsync(artist, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
// The unique artist name index only covers the visible artists, so a new file of a deleted artist materializes as a new visible artist.
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
Assert.Equal(2, await context.Artists.AsNoTracking().CountAsync(candidate => candidate.LibraryId == libraryId && candidate.Name == "Queen"));
Assert.Single(await context.Artists.AsNoTracking().Where(candidate => candidate.LibraryId == libraryId && candidate.Name == "Queen" && !candidate.IsDeleted).ToListAsync());
}
[Fact]
public async Task GetByIdAsync_WhenTheArtistIsSoftDeleted_ShouldReturnNull()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getbyid-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
artist.IsDeleted = true;
artist.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<ArtistEntity?> result = await sut.GetByIdAsync(artist.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByIdAsync_WhenAnAlbumAndATrackAreSoftDeleted_ShouldExcludeThemFromTheGraph()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getbyid-deleted-children-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity activeAlbum = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
TrackEntity activeTrack = _trackEntityFixture.Create(albumId: activeAlbum.Id, libraryId: libraryId, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: activeAlbum.Id, libraryId: libraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
activeAlbum.Tracks = [activeTrack, deletedTrack];
AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
deletedAlbum.Tracks = [_trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false)];
artist.Albums = [activeAlbum, deletedAlbum];
context.Artists.Add(artist);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();
// Act
Result<ArtistEntity?> result = await sut.GetByIdAsync(artist.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistEntity retrievedArtist = result.Value!;
AlbumEntity retrievedAlbum = Assert.Single(retrievedArtist.Albums);
Assert.Equal(activeAlbum.Id, retrievedAlbum.Id);
Assert.Equal(activeTrack.Id, Assert.Single(retrievedAlbum.Tracks).Id);
}
[Fact]
public async Task GetAllAsync_WhenTheArtistIsSoftDeleted_ShouldExcludeIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getall-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity activeArtist = await SeedArtistAsync(context, libraryId, "Queen");
ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId, "Deleted Artist");
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<ArtistEntity>> result = await sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeArtist.Id, Assert.Single(result.Value.Data).Id);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenCalled_ShouldReturnThePersistedDeletionState()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getdeleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
DateTime deletedOnUtc = _mockDateTimeProvider.UtcNow;
artist.IsDeleted = true;
artist.DeletedOnUtc = deletedOnUtc;
await context.SaveChangesAsync();
// Act
Result<ArtistEntity?> result = await sut.GetSoftDeletedByIdAsync(artist.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
Assert.Equal(deletedOnUtc, result.Value!.DeletedOnUtc);
}
[Fact]
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyTheDeletedArtistsOrderedByDeletionTime()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getdeleted-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
DateTime deletedOnUtc = _mockDateTimeProvider.UtcNow;
ArtistEntity olderDeletion = await SeedArtistAsync(context, libraryId, "Older");
olderDeletion.IsDeleted = true;
olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2);
ArtistEntity newerDeletion = await SeedArtistAsync(context, libraryId, "Newer");
newerDeletion.IsDeleted = true;
newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1);
ArtistEntity activeArtist = await SeedArtistAsync(context, libraryId, "Active");
ArtistEntity otherLibraryDeletion = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
otherLibraryDeletion.IsDeleted = true;
otherLibraryDeletion.DeletedOnUtc = deletedOnUtc;
context.Artists.Add(otherLibraryDeletion);
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<ArtistEntity>> result = await sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([newerDeletion.Id, olderDeletion.Id], result.Value.Select(artist => artist.Id));
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenCalled_ShouldPersistTheDeletionStateAndProviderTime()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-softdelete-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
// Act
Result<Updated> result = await sut.SoftDeleteByIdAsync(artist.Id, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
ArtistEntity storedArtist = await context.Artists.AsNoTracking().SingleAsync(candidate => candidate.Id == artist.Id);
Assert.True(storedArtist.IsDeleted);
Assert.Equal(_mockDateTimeProvider.UtcNow, storedArtist.DeletedOnUtc);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldPersistTheClearedDeletionState()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-restore-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
artist.IsDeleted = true;
artist.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.RestoreSoftDeletedByIdAsync(artist.Id, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
ArtistEntity storedArtist = await context.Artists.AsNoTracking().SingleAsync(candidate => candidate.Id == artist.Id);
Assert.False(storedArtist.IsDeleted);
Assert.Null(storedArtist.DeletedOnUtc);
}
[Fact]
public async Task UpdateAsync_WhenTheArtistIsSoftDeleted_ShouldReturnArtistNotFound()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
artist.IsDeleted = true;
artist.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
ArtistEntity data = _artistEntityFixture.Create(id: artist.Id, includeAlbums: false, includeContributors: false);
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenIncomingDataIsMarkedDeleted_ShouldPreserveTheActiveRowsDeletionState()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-preserve-deletion-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
ArtistEntity data = await LoadDetachedArtistAsync(context, artist.Id);
data.Name = "Freddie Mercury";
data.IsDeleted = true;
data.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
ArtistEntity storedArtist = await context.Artists.AsNoTracking().SingleAsync(candidate => candidate.Id == artist.Id);
Assert.Equal("Freddie Mercury", storedArtist.Name);
Assert.False(storedArtist.IsDeleted);
Assert.Null(storedArtist.DeletedOnUtc);
}
[Fact]
public async Task UpdateAsync_WhenAnAlbumIsSoftDeleted_ShouldKeepItAndItsTracks()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-keeps-deleted-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedFullArtistAsync(context, libraryId);
AlbumEntity deletedAlbum = artist.Albums[0];
TrackEntity trackOfDeletedAlbum = deletedAlbum.Tracks[0];
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
ArtistEntity data = _artistEntityFixture.Create(id: artist.Id, includeAlbums: false, includeContributors: false);
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == deletedAlbum.Id);
Assert.True(storedAlbum.IsDeleted);
TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == trackOfDeletedAlbum.Id);
Assert.False(storedTrack.IsDeleted);
}
[Fact]
public async Task UpdateAsync_WhenATrackIsSoftDeleted_ShouldKeepIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-keeps-deleted-track-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedFullArtistAsync(context, libraryId);
TrackEntity deletedTrack = artist.Albums[0].Tracks[0];
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
AlbumEntity incomingAlbum = _albumEntityFixture.Create(
id: artist.Albums[0].Id,
artistId: artist.Id,
libraryId: libraryId,
title: artist.Albums[0].Title,
includeTracks: false,
includeMetadata: false);
ArtistEntity data = _artistEntityFixture.Create(id: artist.Id, includeAlbums: false, includeContributors: false);
data.Albums = [incomingAlbum];
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == deletedTrack.Id);
Assert.True(storedTrack.IsDeleted);
}
[Fact]
public async Task UpdateAsync_WhenIncomingAlbumMatchesASoftDeletedAlbum_ShouldReturnAlbumNotFoundWithoutEditingIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-rejects-deleted-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedFullArtistAsync(context, libraryId);
AlbumEntity deletedAlbum = artist.Albums[0];
string originalTitle = deletedAlbum.Title;
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
AlbumEntity incomingAlbum = _albumEntityFixture.Create(
id: deletedAlbum.Id,
artistId: artist.Id,
libraryId: libraryId,
title: "Edited Hidden Album",
includeTracks: false,
includeMetadata: false);
ArtistEntity data = _artistEntityFixture.Create(id: artist.Id, includeAlbums: false, includeContributors: false);
data.Albums = [incomingAlbum];
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
AlbumEntity storedAlbum = await context.Albums.AsNoTracking().SingleAsync(candidate => candidate.Id == deletedAlbum.Id);
Assert.Equal(originalTitle, storedAlbum.Title);
Assert.True(storedAlbum.IsDeleted);
}
[Fact]
public async Task UpdateAsync_WhenIncomingTrackMatchesASoftDeletedTrack_ShouldReturnTrackNotFoundWithoutEditingIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-rejects-deleted-track-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
ArtistRepository sut = CreateArtistRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedFullArtistAsync(context, libraryId);
AlbumEntity storedAlbum = artist.Albums[0];
TrackEntity deletedTrack = storedAlbum.Tracks[0];
string originalTitle = deletedTrack.Title;
string originalPath = deletedTrack.Path;
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
AlbumEntity incomingAlbum = _albumEntityFixture.Create(
id: storedAlbum.Id,
artistId: artist.Id,
libraryId: libraryId,
title: storedAlbum.Title,
includeTracks: false,
includeMetadata: false);
TrackEntity incomingTrack = _trackEntityFixture.Create(
id: deletedTrack.Id,
albumId: storedAlbum.Id,
libraryId: libraryId,
title: "Edited Hidden Track",
path: "/music/moved-hidden-track.flac",
includeMetadata: false);
incomingAlbum.Tracks = [incomingTrack];
ArtistEntity data = _artistEntityFixture.Create(id: artist.Id, includeAlbums: false, includeContributors: false);
data.Albums = [incomingAlbum];
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == deletedTrack.Id);
Assert.Equal(originalTitle, storedTrack.Title);
Assert.Equal(originalPath, storedTrack.Path);
Assert.True(storedTrack.IsDeleted);
}
/// <summary>
/// Seeds an artist that owns the requested number of albums, each with the requested number of tracks, all of them with distinct shared reference names.
/// </summary>
@@ -1371,11 +1822,11 @@ public class ArtistRepositoryTests
/// </summary>
/// <param name="context">The context the repository operates on.</param>
/// <returns>The created repository.</returns>
private static ArtistRepository CreateArtistRepository(LuminaDbContext context)
private ArtistRepository CreateArtistRepository(LuminaDbContext context)
{
TrackRepository trackRepository = new(context);
AlbumRepository albumRepository = new(context, trackRepository);
return new ArtistRepository(context, albumRepository, trackRepository);
TrackRepository trackRepository = new(context, _mockDateTimeProvider);
AlbumRepository albumRepository = new(context, trackRepository, _mockDateTimeProvider);
return new ArtistRepository(context, albumRepository, trackRepository, _mockDateTimeProvider);
}
/// <summary>
@@ -49,6 +49,16 @@ public class TrackRepositoryTests
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
private readonly IDateTimeProvider _mockDateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="TrackRepositoryTests"/> class.
/// </summary>
public TrackRepositoryTests()
{
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc));
}
[Fact]
public async Task InsertAsync_WhenCalledWithAValidTrack_ShouldPersistTheTrackAndItsChildren()
@@ -58,7 +68,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -107,7 +117,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -133,7 +143,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid firstLibraryId = Guid.NewGuid();
AlbumEntity firstAlbum = await SeedAlbumAsync(context, firstLibraryId);
@@ -165,7 +175,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -198,7 +208,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -226,7 +236,7 @@ public class TrackRepositoryTests
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -275,7 +285,7 @@ public class TrackRepositoryTests
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -319,7 +329,7 @@ public class TrackRepositoryTests
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -360,7 +370,7 @@ public class TrackRepositoryTests
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -402,7 +412,7 @@ public class TrackRepositoryTests
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -444,7 +454,7 @@ public class TrackRepositoryTests
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -504,7 +514,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -545,7 +555,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -572,7 +582,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -626,7 +636,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -675,7 +685,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -707,7 +717,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -752,7 +762,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -780,7 +790,7 @@ public class TrackRepositoryTests
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
@@ -805,7 +815,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-empty-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
context.Tracks.Add(_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false));
@@ -827,7 +837,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity firstTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/first.flac", includeMetadata: false);
@@ -855,7 +865,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/hidden.flac", includeMetadata: false);
@@ -897,7 +907,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-include-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId, includeMetadata: true);
ArtistEntity artist = await context.Artists.AsNoTracking().FirstAsync(candidate => candidate.Id == album.ArtistId);
@@ -941,7 +951,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-chunks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
const int TRACK_COUNT = 501;
@@ -969,7 +979,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -998,7 +1008,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-artist-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity artistAlbum = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1026,7 +1036,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1053,7 +1063,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-bothfilters-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1083,7 +1093,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-excluded-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1109,7 +1119,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-count-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1132,7 +1142,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-fewertracks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1155,7 +1165,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-nomatch-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1178,7 +1188,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-projection-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1214,7 +1224,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-cover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1239,7 +1249,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-nocover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1262,7 +1272,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-noncover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1286,7 +1296,7 @@ public class TrackRepositoryTests
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-othercover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = new(context);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
@@ -1304,8 +1314,607 @@ public class TrackRepositoryTests
Assert.Null(row.CoverPath);
}
[Fact]
public async Task InsertAsync_WhenATrackWithTheSamePathIsSoftDeleted_ShouldReturnTrackAlreadyExists()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-insert-deleted-path-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.Add(deletedTrack);
await context.SaveChangesAsync();
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false);
// Act
Result<Created> result = await sut.InsertAsync(track, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
}
[Fact]
public async Task GetExistingPathsAsync_WhenTheOnlyTrackIsSoftDeleted_ShouldStillReportThePath()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-existing-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.Add(deletedTrack);
await context.SaveChangesAsync();
// Act
Result<IReadOnlyCollection<string>> result = await sut.GetExistingPathsAsync(libraryId, ["/music/queen/deleted.flac"], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(["/music/queen/deleted.flac"], result.Value);
}
[Fact]
public async Task GetByPathAsync_WhenTheTrackIsSoftDeleted_ShouldReturnIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbypath-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.Add(deletedTrack);
await context.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await sut.GetByPathAsync(libraryId, "/music/queen/deleted.flac", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(deletedTrack.Id, result.Value!.Id);
Assert.True(result.Value.IsDeleted);
}
[Fact]
public async Task GetByIdAsync_WhenTheTrackIsSoftDeleted_ShouldReturnNull()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyid-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
track.IsDeleted = true;
track.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.Add(track);
await context.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Theory]
[InlineData(true)] // The album of the track is soft deleted.
[InlineData(false)] // The artist of the album is soft deleted.
public async Task GetByIdAsync_WhenAnAncestorIsSoftDeleted_ShouldReturnNull(bool isAlbumDeleted)
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyid-deleted-ancestor-{isAlbumDeleted}-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
context.Tracks.Add(track);
if (isAlbumDeleted)
album.IsDeleted = true;
else
artist.IsDeleted = true;
await context.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByAlbumIdAsync_WhenTracksAreSoftDeleted_ShouldExcludeThem()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyalbum-deleted-tracks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.AddRange(activeTrack, deletedTrack);
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByAlbumIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeTrack.Id, Assert.Single(result.Value).Id);
}
[Fact]
public async Task GetByAlbumIdAsync_WhenTheAlbumIsSoftDeleted_ShouldReturnEmpty()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyalbum-deleted-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
context.Tracks.Add(track);
album.IsDeleted = true;
album.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByAlbumIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetByAlbumIdIncludingDeletedAsync_WhenCalled_ShouldReturnEveryTrackOfTheAlbumOrdered()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyalbum-including-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, trackNumber: 2, includeMetadata: false);
activeTrack.DiscNumber = 1;
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, trackNumber: 1, includeMetadata: false);
deletedTrack.DiscNumber = 1;
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.AddRange(activeTrack, deletedTrack);
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByAlbumIdIncludingDeletedAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([deletedTrack.Id, activeTrack.Id], result.Value.Select(track => track.Id));
}
[Fact]
public async Task GetShuffleTracksLiteAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity visibleArtist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity visibleAlbum = await SeedAlbumForArtistAsync(context, libraryId, visibleArtist.Id, "A Night at the Opera");
TrackEntity visibleTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.AddRange(visibleTrack, deletedTrack);
ArtistEntity artistOfDeletedAlbum = await SeedArtistAsync(context, libraryId, "Deleted Album Artist");
AlbumEntity deletedAlbum = await SeedAlbumForArtistAsync(context, libraryId, artistOfDeletedAlbum.Id, "Deleted Album");
context.Tracks.Add(_trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false));
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId, "Deleted Artist");
AlbumEntity albumOfDeletedArtist = await SeedAlbumForArtistAsync(context, libraryId, deletedArtist.Id, "Hidden Album");
context.Tracks.Add(_trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false));
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await sut.GetShuffleTracksLiteAsync(libraryId, null, null, [], 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(visibleTrack.Id, Assert.Single(result.Value).TrackId);
}
[Theory]
[InlineData(true)] // The track itself is soft deleted.
[InlineData(false)] // An ancestor of the track is soft deleted.
public async Task GetTrackStreamInfoAsync_WhenTheTrackIsOrHasASoftDeletedAncestor_ShouldReturnNull(bool isTrackDeleted)
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-stream-deleted-{isTrackDeleted}-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
context.Tracks.Add(track);
if (isTrackDeleted)
track.IsDeleted = true;
else
album.IsDeleted = true;
await context.SaveChangesAsync();
// Act
Result<TrackStreamDto?> result = await sut.GetTrackStreamInfoAsync(libraryId, album.Id, artist.Id, track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Theory]
[InlineData(true)] // The track itself is soft deleted.
[InlineData(false)] // An ancestor of the track is soft deleted.
public async Task GetPlaybackManifestInfoAsync_WhenTheTrackIsOrHasASoftDeletedAncestor_ShouldReturnNull(bool isTrackDeleted)
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-manifest-deleted-{isTrackDeleted}-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
context.Tracks.Add(track);
if (isTrackDeleted)
track.IsDeleted = true;
else
artist.IsDeleted = true;
await context.SaveChangesAsync();
// Act
Result<TrackPlaybackManifestDto?> result = await sut.GetPlaybackManifestInfoAsync(libraryId, album.Id, artist.Id, track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetAccessInfoByIdsAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-access-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.AddRange(activeTrack, deletedTrack);
ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId, "Deleted Artist");
AlbumEntity albumOfDeletedArtist = await SeedAlbumForArtistAsync(context, libraryId, deletedArtist.Id, "Hidden Album");
TrackEntity trackOfDeletedArtist = _trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false);
context.Tracks.Add(trackOfDeletedArtist);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<TrackAccessSummaryDto> result = await sut.GetAccessInfoByIdsAsync([activeTrack.Id, deletedTrack.Id, trackOfDeletedArtist.Id], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value.TrackCount);
Assert.Equal([libraryId], result.Value.LibraryIds);
}
[Fact]
public async Task GetByIdsAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyids-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.AddRange(activeTrack, deletedTrack);
ArtistEntity artistOfDeletedAlbum = await SeedArtistAsync(context, libraryId, "Album Artist");
AlbumEntity deletedAlbum = await SeedAlbumForArtistAsync(context, libraryId, artistOfDeletedAlbum.Id, "Deleted Album");
TrackEntity trackOfDeletedAlbum = _trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false);
context.Tracks.Add(trackOfDeletedAlbum);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByIdsAsync([activeTrack.Id, deletedTrack.Id, trackOfDeletedAlbum.Id], false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeTrack.Id, Assert.Single(result.Value).Id);
}
[Fact]
public async Task GetTracksNeedingMetadataCountAsync_WhenATrackOrItsAncestorsAreSoftDeleted_ShouldNotCountIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-count-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
TrackEntity pendingTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.AddRange(pendingTrack, deletedTrack);
ArtistEntity artistOfDeletedAlbum = await SeedArtistAsync(context, libraryId, "Album Artist");
AlbumEntity deletedAlbum = await SeedAlbumForArtistAsync(context, libraryId, artistOfDeletedAlbum.Id, "Deleted Album");
context.Tracks.Add(_trackEntityFixture.Create(
albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending));
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
await context.SaveChangesAsync();
// Act
Result<int> result = await sut.GetTracksNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenCalled_ShouldPersistTheDeletionStateAndProviderTime()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-softdelete-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
context.Tracks.Add(track);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.SoftDeleteByIdAsync(track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == track.Id);
Assert.True(storedTrack.IsDeleted);
Assert.Equal(_mockDateTimeProvider.UtcNow, storedTrack.DeletedOnUtc);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenTrackIsAlreadyDeleted_ShouldReturnTrackNotFound()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-softdelete-already-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
DateTime storedDeletedOnUtc = _mockDateTimeProvider.UtcNow.AddHours(-1);
track.IsDeleted = true;
track.DeletedOnUtc = storedDeletedOnUtc;
context.Tracks.Add(track);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.SoftDeleteByIdAsync(track.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == track.Id);
Assert.Equal(storedDeletedOnUtc, storedTrack.DeletedOnUtc);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenTrackDoesNotExist_ShouldReturnTrackNotFound()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-softdelete-missing-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
// Act
Result<Updated> result = await sut.SoftDeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldPersistTheClearedDeletionState()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-restore-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
track.IsDeleted = true;
track.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.Add(track);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.RestoreSoftDeletedByIdAsync(track.Id, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == track.Id);
Assert.False(storedTrack.IsDeleted);
Assert.Null(storedTrack.DeletedOnUtc);
}
[Fact]
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyDeletedTracksWithVisibleAncestorsOrdered()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getdeleted-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
DateTime deletedOnUtc = _mockDateTimeProvider.UtcNow;
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity olderDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Alpha", includeMetadata: false);
olderDeletion.IsDeleted = true;
olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2);
TrackEntity newerDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Beta", includeMetadata: false);
newerDeletion.IsDeleted = true;
newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1);
TrackEntity sameTimeDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Gamma", includeMetadata: false);
sameTimeDeletion.IsDeleted = true;
sameTimeDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1);
context.Tracks.AddRange(olderDeletion, newerDeletion, sameTimeDeletion);
ArtistEntity deletedArtist = await SeedArtistAsync(context, libraryId, "Deleted Artist");
AlbumEntity albumOfDeletedArtist = await SeedAlbumForArtistAsync(context, libraryId, deletedArtist.Id, "Hidden Album");
TrackEntity hiddenDeletedTrack = _trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false);
hiddenDeletedTrack.IsDeleted = true;
hiddenDeletedTrack.DeletedOnUtc = deletedOnUtc;
context.Tracks.Add(hiddenDeletedTrack);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = deletedOnUtc;
await context.SaveChangesAsync();
TrackEntity[] expectedDeletedTracks = [olderDeletion, newerDeletion, sameTimeDeletion];
Guid[] expectedOrder = [.. expectedDeletedTracks
.OrderByDescending(track => track.DeletedOnUtc)
.ThenByDescending(track => track.Title)
.ThenByDescending(track => track.Id)
.Select(track => track.Id)];
// Act
Result<IReadOnlyList<TrackEntity>> result = await sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedOrder, result.Value.Select(track => track.Id));
}
[Fact]
public async Task UpdateAsync_WhenTheTrackIsSoftDeleted_ShouldReturnTrackNotFound()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
track.IsDeleted = true;
track.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Tracks.Add(track);
await context.SaveChangesAsync();
TrackEntity data = _trackEntityFixture.Create(id: track.Id, albumId: album.Id, libraryId: libraryId, includeMetadata: false);
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenIncomingDataIsMarkedDeleted_ShouldPreserveTheActiveRowsDeletionState()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-preserve-deletion-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
TrackRepository sut = CreateTrackRepository(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
context.Tracks.Add(track);
await context.SaveChangesAsync();
TrackEntity data = await LoadDetachedTrackAsync(context, track.Id);
data.Title = "Somebody to Love";
data.IsDeleted = true;
data.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
// Act
Result<Updated> result = await sut.UpdateAsync(data, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
TrackEntity storedTrack = await context.Tracks.AsNoTracking().SingleAsync(candidate => candidate.Id == track.Id);
Assert.Equal("Somebody to Love", storedTrack.Title);
Assert.False(storedTrack.IsDeleted);
Assert.Null(storedTrack.DeletedOnUtc);
}
/// <summary>
/// Creates a list of tracks with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data.
/// Creates a list of tracks of the provided album with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data.
/// </summary>
/// <param name="count">The number of tracks to create.</param>
/// <param name="albumId">The Id of the album that owns the tracks.</param>
@@ -1317,6 +1926,16 @@ public class TrackRepositoryTests
albumId: albumId, libraryId: libraryId, path: $"/music/generated-{Guid.NewGuid():N}.flac", includeMetadata: false))];
}
/// <summary>
/// Creates a track repository backed by the provided context, using the deterministic time provider of the test class.
/// </summary>
/// <param name="context">The context the repository operates on.</param>
/// <returns>The created repository.</returns>
private TrackRepository CreateTrackRepository(LuminaDbContext context)
{
return new TrackRepository(context, _mockDateTimeProvider);
}
/// <summary>
/// Creates a real SQLite backed context, so that the stored values are read exactly as they were written.
/// </summary>
@@ -44,6 +44,16 @@ public class PlaylistRepositoryTests
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly IDateTimeProvider _mockDateTimeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="PlaylistRepositoryTests"/> class.
/// </summary>
public PlaylistRepositoryTests()
{
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc));
}
[Fact]
public async Task UpdateAsync_WhenNoEditableValueChanged_ShouldNotModifyTheStoredPlaylist()
@@ -741,6 +751,125 @@ public class PlaylistRepositoryTests
Assert.Null(item.Display);
}
[Fact]
public async Task AddScopeEntriesAsync_WhenTheScopeContainsSoftDeletedItems_ShouldAppendOnlyTheVisibleTracks()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-scope-deleted-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
PlaylistRepository sut = new(context);
Guid userId = Guid.NewGuid();
context.Users.Add(_userEntityFixture.Create(id: userId));
Guid libraryId = Guid.NewGuid();
ArtistEntity visibleArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Visible Artist", includeAlbums: false, includeContributors: false);
AlbumEntity visibleAlbum = _albumEntityFixture.Create(artistId: visibleArtist.Id, libraryId: libraryId, title: "Visible Album", includeTracks: false, includeMetadata: false);
TrackEntity visibleTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, title: "Visible Track", includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, title: "Deleted Track", includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
context.Artists.Add(visibleArtist);
context.Albums.Add(visibleAlbum);
context.Tracks.AddRange(visibleTrack, deletedTrack);
ArtistEntity artistOfDeletedAlbum = _artistEntityFixture.Create(libraryId: libraryId, name: "Album Artist", includeAlbums: false, includeContributors: false);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistOfDeletedAlbum.Id, libraryId: libraryId, title: "Deleted Album", includeTracks: false, includeMetadata: false);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
TrackEntity trackOfDeletedAlbum = _trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, title: "Deleted Album Track", includeMetadata: false);
context.Artists.Add(artistOfDeletedAlbum);
context.Albums.Add(deletedAlbum);
context.Tracks.Add(trackOfDeletedAlbum);
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Deleted Artist", includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = _mockDateTimeProvider.UtcNow;
AlbumEntity albumOfDeletedArtist = _albumEntityFixture.Create(artistId: deletedArtist.Id, libraryId: libraryId, title: "Album Of Deleted Artist", includeTracks: false, includeMetadata: false);
TrackEntity trackOfDeletedArtist = _trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, title: "Deleted Artist Track", includeMetadata: false);
context.Artists.Add(deletedArtist);
context.Albums.Add(albumOfDeletedArtist);
context.Tracks.Add(trackOfDeletedArtist);
PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 0, version: 0);
context.Playlists.Add(playlist);
await context.SaveChangesAsync();
// Act
Result<PlaylistBulkAddResultDto> result = await sut.AddScopeEntriesAsync(
playlist.Id,
userId,
libraryId,
artistId: null,
albumId: null,
PlaylistMediaItemType.MusicTrack,
_mockDateTimeProvider.UtcNow,
CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value.AddedCount);
List<Guid> storedMediaItemIds = await context.PlaylistEntries
.AsNoTracking()
.Where(entry => entry.PlaylistId == playlist.Id)
.Select(entry => entry.MediaItemId)
.ToListAsync();
Assert.Equal([visibleTrack.Id], storedMediaItemIds);
}
[Theory]
[InlineData(true)] // The track itself is soft deleted.
[InlineData(false)] // An ancestor of the track is soft deleted.
public async Task GetDetailsForUserAsync_WhenAnEntryReferencesASoftDeletedTrack_ShouldKeepTheEntryWithoutDisplayData(bool isTrackDeleted)
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-details-deleted-{isTrackDeleted}-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = CreateContext(anchorConnection);
PlaylistRepository sut = new(context);
Guid userId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
context.Users.Add(_userEntityFixture.Create(id: userId));
(ArtistEntity artist, AlbumEntity album, TrackEntity track) = await SeedTrackAsync(
context,
libraryId,
artistName: "Deleted Track Artist",
albumTitle: "Deleted Track Album",
trackTitle: "Deleted Track",
coverFileName: "deleted-track-cover.jpg");
if (isTrackDeleted)
track.IsDeleted = true;
else
album.IsDeleted = true;
await context.SaveChangesAsync();
Guid playlistId = Guid.NewGuid();
PlaylistEntryEntity entry = _playlistEntryEntityFixture.Create(
playlistId: playlistId,
mediaItemId: track.Id,
mediaItemType: PlaylistMediaItemType.MusicTrack,
position: 1_000_000_000L);
PlaylistEntity playlist = _playlistEntityFixture.Create(
id: playlistId,
userId: userId,
type: PlaylistType.Music,
entries: [entry],
entryCount: 1,
version: 0);
context.Playlists.Add(playlist);
await context.SaveChangesAsync();
// Act
Result<PlaylistDetailsDto?> result = await sut.GetDetailsForUserAsync(playlistId, userId, paginationData: null, CancellationToken.None);
// Assert
// A deleted item keeps its entry so its owner can see and remove it, but its display data is no longer exposed.
Assert.False(result.IsFailure);
Assert.NotNull(result.Value);
PlaylistEntryDto item = Assert.Single(result.Value!.Entries.Data);
Assert.Equal(entry.Id, item.Entry.Id);
Assert.Null(item.Display);
}
/// <summary>
/// Seeds a playlist of the given user with the requested number of entries, each referencing a different generated media item.
/// </summary>
@@ -82,6 +82,7 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
@@ -92,7 +93,7 @@ public class MusicArtworkServiceTests
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
@@ -104,7 +105,7 @@ public class MusicArtworkServiceTests
.Returns(Result.From(renamedFileId));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -131,6 +132,7 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
@@ -141,7 +143,7 @@ public class MusicArtworkServiceTests
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
@@ -150,7 +152,7 @@ public class MusicArtworkServiceTests
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, expectedFileName))));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -168,6 +170,7 @@ public class MusicArtworkServiceTests
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string albumTitle = "Test Album";
@@ -178,7 +181,7 @@ public class MusicArtworkServiceTests
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName: "Unknown", albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName: "Unknown", albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
@@ -187,11 +190,11 @@ public class MusicArtworkServiceTests
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockPathService.Received(1).SanitizeSegment("Unknown");
_mockPathService.Received(1).SanitizeCompositeSegment("Unknown", artistId.ToString());
}
finally
{
@@ -218,7 +221,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -246,7 +249,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -272,7 +275,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -293,6 +296,7 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
@@ -300,7 +304,7 @@ public class MusicArtworkServiceTests
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
@@ -309,7 +313,7 @@ public class MusicArtworkServiceTests
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -327,7 +331,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -342,7 +346,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -356,6 +360,7 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
@@ -366,7 +371,7 @@ public class MusicArtworkServiceTests
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
@@ -375,7 +380,7 @@ public class MusicArtworkServiceTests
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -402,7 +407,7 @@ public class MusicArtworkServiceTests
// Act
async Task Act()
{
await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, cancellationTokenSource.Token);
await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, cancellationTokenSource.Token);
}
// Assert
@@ -422,7 +427,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -442,6 +447,7 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
@@ -452,13 +458,13 @@ public class MusicArtworkServiceTests
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -478,6 +484,7 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
@@ -488,13 +495,13 @@ public class MusicArtworkServiceTests
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -514,6 +521,7 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
@@ -524,13 +532,13 @@ public class MusicArtworkServiceTests
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -550,6 +558,7 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
@@ -560,7 +569,7 @@ public class MusicArtworkServiceTests
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
@@ -568,7 +577,7 @@ public class MusicArtworkServiceTests
.Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -587,6 +596,7 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
@@ -603,17 +613,18 @@ public class MusicArtworkServiceTests
_mockPathService.CombinePath(mediaRoot, "music").Returns(Result.From(musicPath));
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
_mockPathService.SanitizeSegment(Arg.Any<string>())
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.Arg<string>();
return name == $"{libraryName}-{libraryId}"
? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false))
: Errors.FileSystemManagement.InvalidPath;
string name = callInfo.ArgAt<string>(0);
string identifier = callInfo.ArgAt<string>(1);
return name == artistName
? Errors.FileSystemManagement.InvalidPath
: Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
});
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -633,10 +644,11 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
@@ -646,7 +658,7 @@ public class MusicArtworkServiceTests
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle);
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
// Assert
Assert.False(result.IsFailure);
@@ -661,11 +673,12 @@ public class MusicArtworkServiceTests
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string libraryName = "Test Library";
Guid artistId = Guid.NewGuid();
string artistName = "Test Artist";
string albumTitle = "Test Album";
byte[] uploadedBytes = [10, 20, 30, 40, 50];
string libraryDirectoryPath = BuildLibraryDirectoryPath(libraryName, libraryId);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
string expectedStoredPath = Path.Combine(artworkDirectoryPath, "cover.jpg");
string? temporaryUploadPath = null;
MockRealFileSystemStubs(pathId => temporaryUploadPath = pathId.Path);
@@ -675,7 +688,7 @@ public class MusicArtworkServiceTests
try
{
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -699,11 +712,12 @@ public class MusicArtworkServiceTests
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
byte[] uploadedBytes = [60, 70, 80, 90];
string libraryDirectoryPath = BuildLibraryDirectoryPath(libraryName, libraryId);
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName);
string expectedStoredPath = Path.Combine(artworkDirectoryPath, "cover.png");
string? temporaryUploadPath = null;
MockRealFileSystemStubs(pathId => temporaryUploadPath = pathId.Path);
@@ -713,7 +727,7 @@ public class MusicArtworkServiceTests
try
{
// Act
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None);
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, artworkStream, "cover.png", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -732,6 +746,44 @@ public class MusicArtworkServiceTests
}
}
[Fact]
public async Task SaveArtistArtworkAsync_WhenTwoArtistsShareTheSameName_ShouldStoreTheirArtworkInDifferentDirectories()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid firstArtistId = Guid.NewGuid();
Guid secondArtistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Queen";
string libraryDirectoryPath = BuildLibraryDirectoryPath(libraryName, libraryId);
string firstArtworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, firstArtistId, artistName);
string secondArtworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, secondArtistId, artistName);
MockRealFileSystemStubs();
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
await using MemoryStream firstArtworkStream = new([1, 2, 3]);
await using MemoryStream secondArtworkStream = new([4, 5, 6]);
try
{
// Act
Result<string> firstResult = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, firstArtistId, artistName, firstArtworkStream, "cover.png", CancellationToken.None);
Result<string> secondResult = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, secondArtistId, artistName, secondArtworkStream, "cover.png", CancellationToken.None);
// Assert
// A visible artist and a deleted artist can share a name, so the artist Id keeps their artwork apart and replacing the cover of one never touches the file of the other.
Assert.False(firstResult.IsFailure);
Assert.False(secondResult.IsFailure);
Assert.NotEqual(firstResult.Value, secondResult.Value);
Assert.True(File.Exists(Path.Combine(firstArtworkDirectoryPath, "cover.png")));
Assert.True(File.Exists(Path.Combine(secondArtworkDirectoryPath, "cover.png")));
}
finally
{
if (Directory.Exists(libraryDirectoryPath))
Directory.Delete(libraryDirectoryPath, recursive: true);
}
}
[Fact]
public void DeleteStoredArtwork_WhenTheFileExists_ShouldDeleteTheRealFile()
{
@@ -853,6 +905,14 @@ public class MusicArtworkServiceTests
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
});
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.ArgAt<string>(0);
string identifier = callInfo.ArgAt<string>(1);
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
});
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
}
@@ -881,17 +941,18 @@ public class MusicArtworkServiceTests
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="albumId">The Id of the album.</param>
/// <param name="libraryName">The name of the media library the album belongs to.</param>
/// <param name="artistId">The Id of the artist of the album.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param>
/// <returns>The expected file system path of the album artwork directory.</returns>
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle)
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle)
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"music",
$"{libraryName}-{libraryId}",
artistName,
$"{artistName}-{artistId}",
$"{albumTitle}-{albumId}");
}
@@ -915,16 +976,17 @@ public class MusicArtworkServiceTests
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
/// <param name="artistName">The name of the artist.</param>
/// <returns>The expected file system path of the artist artwork directory.</returns>
private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName)
private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, Guid artistId, string artistName)
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"music",
$"{libraryName}-{libraryId}",
artistName);
$"{artistName}-{artistId}");
}
/// <summary>
@@ -561,14 +561,15 @@ public class BookArtworkServiceTests
_mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath));
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
_mockPathService.SanitizeSegment(Arg.Any<string>())
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.Arg<string>();
return name == $"{libraryName}-{libraryId}"
? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false))
: Errors.FileSystemManagement.InvalidPath;
string name = callInfo.ArgAt<string>(0);
string identifier = callInfo.ArgAt<string>(1);
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
});
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(Errors.FileSystemManagement.InvalidPath);
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
@@ -602,6 +603,14 @@ public class BookArtworkServiceTests
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
});
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.ArgAt<string>(0);
string identifier = callInfo.ArgAt<string>(1);
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
});
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
@@ -61,7 +61,7 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
}
[Fact]
public async Task DeleteAlbum_WhenAlbumBelongsToAnOwnedArtist_ShouldDeleteTheAlbum()
public async Task DeleteAlbum_WhenAlbumBelongsToAnOwnedArtist_ShouldSoftDeleteTheAlbum()
{
// Arrange
Guid userId = GetCurrentUserId();
@@ -75,13 +75,18 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId));
// The sibling album of the artist is preserved.
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == otherAlbumId));
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
Assert.NotNull(album);
Assert.True(album!.IsDeleted);
Assert.NotNull(album.DeletedOnUtc);
// The sibling album of the artist is untouched.
AlbumEntity? otherAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == otherAlbumId);
Assert.NotNull(otherAlbum);
Assert.False(otherAlbum!.IsDeleted);
}
[Fact]
public async Task DeleteAlbum_WhenAlbumHasStoredArtwork_ShouldRemoveTheArtworkOfTheAlbumAndOfItsTracks()
public async Task DeleteAlbum_WhenAlbumHasStoredArtwork_ShouldKeepTheArtworkOfTheAlbumAndOfItsTracks()
{
// Arrange
Guid userId = GetCurrentUserId();
@@ -97,9 +102,34 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
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));
// The album is soft deleted, so its artwork and the artwork of its tracks stay available until the user restores it.
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
Assert.NotNull(album);
Assert.True(album!.IsDeleted);
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId));
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
}
[Fact]
public async Task DeleteAlbum_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnForbiddenWithoutDeletingTheAlbum()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistWithSingleAlbumAsync(userId);
string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Forbidden", "ArtistMustHaveAtLeastOneAlbum", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
Assert.NotNull(album);
Assert.False(album!.IsDeleted);
Assert.Null(album.DeletedOnUtc);
}
[Fact]
@@ -287,6 +317,36 @@ public class DeleteAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that owns a single album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistWithSingleAlbumAsync(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();
AlbumEntity album = _albumEntityFixture.Create(
id: albumId,
artistId: artistId,
libraryId: libraryId,
title: "A Night at the Opera",
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], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that owns two albums.
/// </summary>
@@ -0,0 +1,250 @@
#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.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums;
/// <summary>
/// Contains integration tests for the <see cref="GetDeletedAlbumsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedAlbumsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedAlbumsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedAlbumsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetDeletedAlbums_WhenLibraryHasDeletedAlbums_ShouldReturnOnlyTheDeletedAlbums()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, name: "Queen");
AlbumEntity deletedAlbum = await SeedAlbumAsync(libraryId, artistId, title: "A Night at the Opera", isDeleted: true);
await SeedAlbumAsync(libraryId, artistId, title: "News of the World", isDeleted: false);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/albums/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
DeletedAlbumResponse[]? albums = await response.Content.ReadFromJsonAsync<DeletedAlbumResponse[]>(_jsonOptions);
Assert.NotNull(albums);
Assert.Single(albums);
Assert.Equal(deletedAlbum.Id, albums![0].Id);
Assert.Equal(libraryId, albums[0].LibraryId);
Assert.Equal(artistId, albums[0].ArtistId);
Assert.Equal("Queen", albums[0].ArtistName);
Assert.Equal("A Night at the Opera", albums[0].Title);
Assert.NotEqual(default, albums[0].DeletedOnUtc);
}
[Fact]
public async Task GetDeletedAlbums_WhenAlbumBelongsToDeletedArtist_ShouldNotReturnIt()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
Guid artistId = await SeedArtistAsync(libraryId, name: "Queen");
await SeedAlbumAsync(libraryId, artistId, title: "A Night at the Opera", isDeleted: true);
await SoftDeleteArtistAsync(artistId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/albums/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
DeletedAlbumResponse[]? albums = await response.Content.ReadFromJsonAsync<DeletedAlbumResponse[]>(_jsonOptions);
Assert.NotNull(albums);
Assert.Empty(albums);
}
[Fact]
public async Task GetDeletedAlbums_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/albums/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task GetDeletedAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/albums/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task GetDeletedAlbums_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/albums/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist in the provided library.
/// </summary>
/// <param name="libraryId">The Id of the library that owns the artist.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>The Id of the seeded artist.</returns>
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false);
dbContext.Artists.Add(artist);
await dbContext.SaveChangesAsync();
return artist.Id;
}
/// <summary>
/// Seeds an album of the provided artist, in the requested deletion state.
/// </summary>
/// <param name="libraryId">The Id of the library that owns the album.</param>
/// <param name="artistId">The Id of the artist that owns the album.</param>
/// <param name="title">The title of the album.</param>
/// <param name="isDeleted">Whether the album is soft deleted.</param>
/// <returns>The seeded album.</returns>
private async Task<AlbumEntity> SeedAlbumAsync(Guid libraryId, Guid artistId, string title, bool isDeleted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: title,
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
album.IsDeleted = isDeleted;
album.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
dbContext.Albums.Add(album);
await dbContext.SaveChangesAsync();
return album;
}
/// <summary>
/// Soft deletes the artist identified by <paramref name="artistId"/>.
/// </summary>
/// <param name="artistId">The Id of the artist to soft delete.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SoftDeleteArtistAsync(Guid artistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ArtistEntity artist = await dbContext.Artists.FirstAsync(artist => artist.Id == artistId);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,246 @@
#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.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum;
/// <summary>
/// Contains integration tests for the <see cref="RestoreAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreAlbumEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreAlbumEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreAlbumEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task RestoreAlbum_WhenDeletedAlbumBelongsToAnOwnedArtist_ShouldRestoreTheAlbum()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
Assert.NotNull(album);
Assert.False(album!.IsDeleted);
Assert.Null(album.DeletedOnUtc);
}
[Fact]
public async Task RestoreAlbum_WhenAlbumIsNotDeleted_ShouldReturnAlbumNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: false);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreAlbum_WhenAlbumIsRestoredThroughDifferentLibrary_ShouldReturnAlbumNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreAlbum_WhenAlbumIsRestoredThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, _, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task RestoreAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task RestoreAlbum_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.PostAsync("/api/v1/libraries/not-a-guid/artists/not-a-guid/albums/not-a-guid/restore", null);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, an artist of it and an album of the artist, in the requested deletion state.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="isDeleted">Whether the seeded album is soft deleted.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, bool isDeleted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: "A Night at the Opera",
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
album.IsDeleted = isDeleted;
album.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
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, album.Id);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -61,7 +61,7 @@ public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
}
[Fact]
public async Task DeleteArtist_WhenArtistBelongsToAnOwnedLibrary_ShouldDeleteTheArtist()
public async Task DeleteArtist_WhenArtistBelongsToAnOwnedLibrary_ShouldSoftDeleteTheArtist()
{
// Arrange
Guid userId = GetCurrentUserId();
@@ -75,11 +75,14 @@ public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId));
ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
Assert.NotNull(artist);
Assert.True(artist!.IsDeleted);
Assert.NotNull(artist.DeletedOnUtc);
}
[Fact]
public async Task DeleteArtist_WhenArtistHasStoredArtwork_ShouldRemoveTheArtworkOfTheArtistAndOfItsChildren()
public async Task DeleteArtist_WhenArtistHasStoredArtwork_ShouldKeepTheArtworkOfTheArtistAndOfItsChildren()
{
// Arrange
Guid userId = GetCurrentUserId();
@@ -96,13 +99,15 @@ public class DeleteArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFac
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));
// The artist is soft deleted, so its albums, tracks and artwork stay available until the user restores it.
ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
Assert.NotNull(artist);
Assert.True(artist!.IsDeleted);
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId));
Assert.NotNull(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId));
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId));
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId));
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
}
[Fact]
@@ -0,0 +1,183 @@
#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.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists;
/// <summary>
/// Contains integration tests for the <see cref="GetDeletedArtistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedArtistsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedArtistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedArtistsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetDeletedArtists_WhenLibraryHasDeletedArtists_ShouldReturnOnlyTheDeletedArtists()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
ArtistEntity deletedArtist = await SeedArtistAsync(libraryId, name: "Queen", isDeleted: true);
await SeedArtistAsync(libraryId, name: "David Bowie", isDeleted: false);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
DeletedArtistResponse[]? artists = await response.Content.ReadFromJsonAsync<DeletedArtistResponse[]>(_jsonOptions);
Assert.NotNull(artists);
Assert.Single(artists);
Assert.Equal(deletedArtist.Id, artists![0].Id);
Assert.Equal(libraryId, artists[0].LibraryId);
Assert.Equal("Queen", artists[0].Name);
Assert.NotEqual(default, artists[0].DeletedOnUtc);
}
[Fact]
public async Task GetDeletedArtists_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/artists/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task GetDeletedArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task GetDeletedArtists_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/artists/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist in the provided library, in the requested deletion state.
/// </summary>
/// <param name="libraryId">The Id of the library that owns the artist.</param>
/// <param name="name">The name of the artist.</param>
/// <param name="isDeleted">Whether the artist is soft deleted.</param>
/// <returns>The seeded artist.</returns>
private async Task<ArtistEntity> SeedArtistAsync(Guid libraryId, string name, bool isDeleted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false);
artist.IsDeleted = isDeleted;
artist.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
dbContext.Artists.Add(artist);
await dbContext.SaveChangesAsync();
return artist;
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,220 @@
#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.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist;
/// <summary>
/// Contains integration tests for the <see cref="RestoreArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreArtistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreArtistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task RestoreArtist_WhenDeletedArtistBelongsToAnOwnedLibrary_ShouldRestoreTheArtist()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
Assert.NotNull(artist);
Assert.False(artist!.IsDeleted);
Assert.Null(artist.DeletedOnUtc);
}
[Fact]
public async Task RestoreArtist_WhenArtistIsNotDeleted_ShouldReturnArtistNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId, isDeleted: false);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreArtist_WhenArtistIsRestoredThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid artistId) = await SeedLibraryAndArtistAsync(userId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task RestoreArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task RestoreArtist_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.PostAsync("/api/v1/libraries/not-a-guid/artists/not-a-guid/restore", null);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and an artist of it, in the requested deletion state.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="isDeleted">Whether the seeded artist is soft deleted.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId, bool isDeleted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
artist.IsDeleted = isDeleted;
artist.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(artist);
await dbContext.SaveChangesAsync();
return (libraryId, artist.Id);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
@@ -64,7 +63,7 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
}
[Fact]
public async Task DeleteTrack_WhenTrackBelongsToAnOwnedLibrary_ShouldDeleteTheTrack()
public async Task DeleteTrack_WhenTrackBelongsToAnOwnedLibrary_ShouldSoftDeleteTheTrack()
{
// Arrange
Guid userId = GetCurrentUserId();
@@ -78,14 +77,21 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Null(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId));
// The album and the artist that contained the track are preserved.
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId));
Assert.NotNull(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId));
TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId);
Assert.NotNull(track);
Assert.True(track!.IsDeleted);
Assert.NotNull(track.DeletedOnUtc);
// The album and the artist that contained the track are untouched.
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
Assert.NotNull(album);
Assert.False(album!.IsDeleted);
Assert.NotNull(artist);
Assert.False(artist!.IsDeleted);
}
[Fact]
public async Task DeleteTrack_WhenTrackHasStoredArtwork_ShouldRemoveItsArtworkRecords()
public async Task DeleteTrack_WhenTrackHasStoredArtwork_ShouldKeepItsArtworkRecords()
{
// Arrange
Guid userId = GetCurrentUserId();
@@ -100,8 +106,11 @@ public class DeleteTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
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));
// The track is soft deleted, so its artwork stays available until the user restores it.
TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId);
Assert.NotNull(track);
Assert.True(track!.IsDeleted);
Assert.NotNull(await dbContext.MusicArtwork.FirstOrDefaultAsync(artwork => artwork.OwnerType == MusicArtworkOwnerType.Track && artwork.OwnerId == trackId));
}
[Fact]
@@ -0,0 +1,264 @@
#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.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks;
/// <summary>
/// Contains integration tests for the <see cref="GetDeletedTracksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedTracksEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedTracksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedTracksEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetDeletedTracks_WhenLibraryHasDeletedTracks_ShouldReturnOnlyTheDeletedTracks()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
TrackEntity deletedTrack = await SeedTrackAsync(libraryId, albumId, title: "Bohemian Rhapsody", path: $"/music/queen/{Guid.NewGuid():N}.flac", isDeleted: true);
await SeedTrackAsync(libraryId, albumId, title: "Love of My Life", path: $"/music/queen/{Guid.NewGuid():N}.flac", isDeleted: false);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/tracks/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
DeletedTrackResponse[]? tracks = await response.Content.ReadFromJsonAsync<DeletedTrackResponse[]>(_jsonOptions);
Assert.NotNull(tracks);
Assert.Single(tracks);
Assert.Equal(deletedTrack.Id, tracks![0].Id);
Assert.Equal(libraryId, tracks[0].LibraryId);
Assert.Equal(artistId, tracks[0].ArtistId);
Assert.Equal("Queen", tracks[0].ArtistName);
Assert.Equal(albumId, tracks[0].AlbumId);
Assert.Equal("A Night at the Opera", tracks[0].AlbumTitle);
Assert.Equal("Bohemian Rhapsody", tracks[0].Title);
Assert.Equal(deletedTrack.Path, tracks[0].Path);
Assert.NotEqual(default, tracks[0].DeletedOnUtc);
}
[Fact]
public async Task GetDeletedTracks_WhenTrackBelongsToDeletedAlbum_ShouldNotReturnIt()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, _, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
await SeedTrackAsync(libraryId, albumId, title: "Bohemian Rhapsody", path: $"/music/queen/{Guid.NewGuid():N}.flac", isDeleted: true);
await SoftDeleteAlbumAsync(albumId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/tracks/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
DeletedTrackResponse[]? tracks = await response.Content.ReadFromJsonAsync<DeletedTrackResponse[]>(_jsonOptions);
Assert.NotNull(tracks);
Assert.Empty(tracks);
}
[Fact]
public async Task GetDeletedTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{otherLibraryId}/tracks/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task GetDeletedTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/tracks/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task GetDeletedTracks_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/not-a-guid/tracks/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, an artist of it and an album of the artist.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: "A Night at the Opera",
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], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, album.Id);
}
/// <summary>
/// Seeds a track of the provided album, in the requested deletion state.
/// </summary>
/// <param name="libraryId">The Id of the library that owns the track.</param>
/// <param name="albumId">The Id of the album that owns the track.</param>
/// <param name="title">The title of the track.</param>
/// <param name="path">The file system path of the track.</param>
/// <param name="isDeleted">Whether the track is soft deleted.</param>
/// <returns>The seeded track.</returns>
private async Task<TrackEntity> SeedTrackAsync(Guid libraryId, Guid albumId, string title, string path, bool isDeleted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
TrackEntity track = _trackEntityFixture.Create(
albumId: albumId,
libraryId: libraryId,
path: path,
title: title,
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
track.IsDeleted = isDeleted;
track.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
dbContext.Tracks.Add(track);
await dbContext.SaveChangesAsync();
return track;
}
/// <summary>
/// Soft deletes the album identified by <paramref name="albumId"/>.
/// </summary>
/// <param name="albumId">The Id of the album to soft delete.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SoftDeleteAlbumAsync(Guid albumId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity album = await dbContext.Albums.FirstAsync(album => album.Id == albumId);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -0,0 +1,258 @@
#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.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack;
/// <summary>
/// Contains integration tests for the <see cref="RestoreTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
{
private HttpClient _client;
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreTrackEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreTrackEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task RestoreTrack_WhenDeletedTrackBelongsToAnOwnedAlbum_ShouldRestoreTheTrack()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId);
Assert.NotNull(track);
Assert.False(track!.IsDeleted);
Assert.Null(track.DeletedOnUtc);
}
[Fact]
public async Task RestoreTrack_WhenTrackIsNotDeleted_ShouldReturnTrackNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: false);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreTrack_WhenTrackIsRestoredThroughDifferentLibrary_ShouldReturnTrackNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreTrack_WhenTrackIsRestoredThroughDifferentAlbum_ShouldReturnTrackNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/{trackId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
{
// Arrange
Guid otherUserId = await SeedOtherUserAsync();
(Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, Guid otherTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, isDeleted: true);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/{otherTrackId}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task RestoreTrack_WhenTrackDoesNotExist_ShouldReturnTrackNotFoundProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
// Act
HttpResponseMessage response = await _client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task RestoreTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await unauthenticatedClient.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task RestoreTrack_WhenIdsAreNotParseable_ShouldReturnUnprocessableEntity()
{
// Act
HttpResponseMessage response = await _client.PostAsync("/api/v1/libraries/not-a-guid/artists/not-a-guid/albums/not-a-guid/tracks/not-a-guid/restore", null);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, an artist of it, an album of the artist and a track of the album, in the requested deletion state.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="isDeleted">Whether the seeded track is soft deleted.</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, bool isDeleted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(
albumId: albumId,
libraryId: libraryId,
path: $"/music/queen/{Guid.NewGuid():N}.flac",
title: "Bohemian Rhapsody",
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
track.IsDeleted = isDeleted;
track.DeletedOnUtc = isDeleted ? DateTime.UtcNow.AddMinutes(-5) : null;
AlbumEntity album = _albumEntityFixture.Create(
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, album.Id, track.Id);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
await dbContext.SaveChangesAsync();
return userId;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -87,6 +87,34 @@ public class GetThemeTemplateEndpointTests : IClassFixture<AuthenticatedLuminaAp
Assert.Contains("restoreUrlTemplate", result.Template);
}
[Theory]
[InlineData("lumina-default")]
[InlineData("editorial-paper")]
public async Task GetThemeTemplate_WhenCalledForTheMusicDeletedItemsPage_ShouldReturnTheBundledTemplateWithItsRestoreHooks(string themeId)
{
// Arrange
await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory);
HttpClient anonymousClient = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await anonymousClient.GetAsync($"/api/v1/themes/{themeId}/templates/library/audio-library/music-library/deleted-items");
// Assert
response.EnsureSuccessStatusCode();
ThemeTemplateResponse? result = await response.Content.ReadFromJsonAsync<ThemeTemplateResponse>(_jsonOptions);
Assert.NotNull(result);
Assert.Equal(themeId, result!.Theme.ThemeId);
Assert.Contains("deleted-artists-table", result.Template);
Assert.Contains("deleted-albums-table", result.Template);
Assert.Contains("deleted-tracks-table", result.Template);
Assert.Contains("btn-restore-artist", result.Template);
Assert.Contains("btn-restore-album", result.Template);
Assert.Contains("btn-restore-track", result.Template);
Assert.Contains("pageData.artistRestoreUrl", result.Template);
Assert.Contains("pageData.albumRestoreUrl", result.Template);
Assert.Contains("pageData.trackRestoreUrl", result.Template);
}
[Fact]
public async Task GetThemeTemplate_WhenThemeDoesNotExist_ShouldReturnNotFound()
{
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
/// <summary>
/// Contains integration tests for the <see cref="RestoreMusicAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicAlbumEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public RestoreMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task RestoreMusicAlbum_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, albumId, libraryId);
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
}
[Fact]
public async Task RestoreMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
_apiFactory.ApiClientStub.Reset();
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
[Fact]
public async Task RestoreMusicAlbum_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
/// <summary>
/// Builds the restore request for the album identified by the route, with the owning library passed through the query string.
/// </summary>
/// <param name="artistId">The route Id of the artist the album belongs to.</param>
/// <param name="albumId">The route Id of the album to restore.</param>
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <returns>The configured restore request.</returns>
private static HttpRequestMessage CreateRestoreRequest(Guid artistId, Guid albumId, Guid libraryId)
{
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/api-restore-album?libraryId={libraryId}")
{
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return restoreRequest;
}
}
@@ -0,0 +1,111 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
/// <summary>
/// Contains integration tests for the <see cref="RestoreMusicArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public RestoreMusicArtistEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task RestoreMusicArtist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{libraryId}/artists/{artistId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, libraryId);
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
}
[Fact]
public async Task RestoreMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
_apiFactory.ApiClientStub.Reset();
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid());
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
[Fact]
public async Task RestoreMusicArtist_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid());
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
/// <summary>
/// Builds the restore request for the artist identified by the route, with the owning library passed through the query string.
/// </summary>
/// <param name="artistId">The route Id of the artist to restore.</param>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <returns>The configured restore request.</returns>
private static HttpRequestMessage CreateRestoreRequest(Guid artistId, Guid libraryId)
{
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{artistId}/api-restore-artist?libraryId={libraryId}")
{
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return restoreRequest;
}
}
@@ -0,0 +1,148 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
/// <summary>
/// Contains integration tests for the <see cref="DeletedMusicItemsViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedMusicItemsViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
private readonly DeletedMusicArtistDtoFixture _deletedMusicArtistDtoFixture = new();
private readonly DeletedMusicAlbumDtoFixture _deletedMusicAlbumDtoFixture = new();
private readonly DeletedMusicTrackDtoFixture _deletedMusicTrackDtoFixture = new();
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeletedMusicItemsViewEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public DeletedMusicItemsViewEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task DeletedMusicItemsView_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderDeletedMusicItemsPage()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Music");
DeletedMusicArtistDto deletedArtist = _deletedMusicArtistDtoFixture.Create(libraryId: libraryId, id: artistId, name: "Deleted Artist");
DeletedMusicAlbumDto deletedAlbum = _deletedMusicAlbumDtoFixture.Create(libraryId: libraryId, id: albumId, artistId: artistId, artistName: "Deleted Artist", title: "Deleted Album");
DeletedMusicTrackDto deletedTrack = _deletedMusicTrackDtoFixture.Create(libraryId: libraryId, artistId: artistId, artistName: "Deleted Artist", albumId: albumId, albumTitle: "Deleted Album", title: "Deleted Track");
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/deleted-items", new[] { deletedArtist });
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/albums/deleted-items", new[] { deletedAlbum });
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/tracks/deleted-items", new[] { deletedTrack });
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={libraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
Assert.Contains("deleted-artists-table", content);
Assert.Contains("deleted-albums-table", content);
Assert.Contains("deleted-tracks-table", content);
Assert.Contains("btn-restore-artist", content);
Assert.Contains("btn-restore-album", content);
Assert.Contains("btn-restore-track", content);
Assert.Contains("Deleted Artist", content);
Assert.Contains("Deleted Album", content);
Assert.Contains("Deleted Track", content);
Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
Assert.Contains($"libraries/{libraryId}/artists/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled);
Assert.Contains($"libraries/{libraryId}/albums/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled);
Assert.Contains($"libraries/{libraryId}/tracks/deleted-items", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task DeletedMusicItemsView_WhenDeletedItemNamesContainMarkup_ShouldEncodeThem()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Music");
DeletedMusicArtistDto deletedArtist = _deletedMusicArtistDtoFixture.Create(libraryId: libraryId, name: "<script>alert('x')</script>");
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artists/deleted-items", new[] { deletedArtist });
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/albums/deleted-items", Array.Empty<DeletedMusicAlbumDto>());
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/tracks/deleted-items", Array.Empty<DeletedMusicTrackDto>());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={libraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Contains("&lt;script&gt;alert", content);
Assert.DoesNotContain("<script>alert('x')</script>", content);
}
[Fact]
public async Task DeletedMusicItemsView_WhenTheApiReturnsForbidden_ShouldRedirectWithoutLeakingDetails()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
LibraryDto library = _libraryDtoFixture.Create(id: libraryId, title: "Music");
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", library);
string endpoint = $"libraries/{libraryId}/artists/deleted-items";
_apiFactory.ApiClientStub.RegisterGetException(endpoint, new ApiException(
_problemDetailsDtoFixture.Create(title: "General.Unauthorized", detail: "NotAuthorized"),
HttpStatusCode.Forbidden,
endpoint));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={libraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// A browser navigation that the API forbids is redirected to the access denied page, without rendering any of the forbidden data.
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
Assert.NotNull(response.Headers.Location);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task DeletedMusicItemsView_WhenCalledWithoutLibraryId_ShouldRedirectToHome()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/audio-library/music-library/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("/en-us", response.Headers.Location!.ToString());
}
}
@@ -0,0 +1,115 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
/// <summary>
/// Contains integration tests for the <see cref="RestoreMusicTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicTrackEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public RestoreMusicTrackEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task RestoreMusicTrack_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardPostAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId, albumId, trackId, libraryId);
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.True(json.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
Assert.Contains($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
}
[Fact]
public async Task RestoreMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
_apiFactory.ApiClientStub.Reset();
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
[Fact]
public async Task RestoreMusicTrack_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
/// <summary>
/// Builds the restore request for the track identified by the route, with the owning library passed through the query string.
/// </summary>
/// <param name="artistId">The route Id of the artist the track belongs to.</param>
/// <param name="albumId">The route Id of the album the track belongs to.</param>
/// <param name="trackId">The route Id of the track to restore.</param>
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
/// <returns>The configured restore request.</returns>
private static HttpRequestMessage CreateRestoreRequest(Guid artistId, Guid albumId, Guid trackId, Guid libraryId)
{
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-restore-track?libraryId={libraryId}")
{
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return restoreRequest;
}
}
@@ -0,0 +1,157 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
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.GetDeletedAlbums;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums;
/// <summary>
/// Contains security tests for the <see cref="GetDeletedAlbumsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedAlbumsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedAlbumsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedAlbumsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetDeletedAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/albums/deleted-items";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task GetDeletedAlbums_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/albums/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetDeletedAlbums_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedAlbum()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
const string TITLE = "Secret Deleted Album";
const string COVER_PATH = "/private/deleted-album-cover.jpg";
Guid libraryId = await SeedLibraryAndDeletedAlbumAsync(victimUserId, TITLE, COVER_PATH);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/albums/deleted-items");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain(TITLE, content, StringComparison.Ordinal);
Assert.DoesNotContain(COVER_PATH, content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with a deleted album, its artist and its cover.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the deleted album.</param>
/// <param name="coverPath">The stored cover path of the deleted album.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAndDeletedAlbumAsync(Guid userId, string title, string coverPath)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: title,
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false));
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverPath));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,241 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum;
/// <summary>
/// Contains security tests for the <see cref="RestoreAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreAlbumEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreAlbumEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreAlbumEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task RestoreAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore";
// Act
HttpResponseMessage response = await _client.PostAsync(url, null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task RestoreAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task RestoreAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task RestoreAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Fact]
public async Task RestoreAlbum_WhenAlbumBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndDeletedAlbumAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
Assert.NotNull(album);
Assert.True(album!.IsDeleted);
}
[Fact]
public async Task RestoreAlbum_WhenAlbumIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
Guid ownLibraryId = await SeedLibraryAsync(actingUserId);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistAndDeletedAlbumAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity? victimAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId);
Assert.NotNull(victimAlbum);
Assert.True(victimAlbum!.IsDeleted);
}
/// <summary>
/// Asserts that a route parameter carrying an injection payload is rejected as a validation error, without leaking internal details.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private async Task AssertRejectedInjectionAttemptAsync(HttpResponseMessage response)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Acting Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and a deleted album of that artist.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndDeletedAlbumAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: "Victim Album",
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, album.Id);
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,145 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
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.GetDeletedArtists;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists;
/// <summary>
/// Contains security tests for the <see cref="GetDeletedArtistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedArtistsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedArtistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedArtistsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetDeletedArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/deleted-items";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task GetDeletedArtists_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetDeletedArtists_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedArtist()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
const string NAME = "Secret Deleted Artist";
const string COVER_PATH = "/private/deleted-artist-cover.jpg";
Guid libraryId = await SeedLibraryAndDeletedArtistAsync(victimUserId, NAME, COVER_PATH);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/artists/deleted-items");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain(NAME, content, StringComparison.Ordinal);
Assert.DoesNotContain(COVER_PATH, content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with a deleted artist and its cover.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="name">The name of the deleted artist.</param>
/// <param name="coverPath">The stored cover path of the deleted artist.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAndDeletedArtistAsync(Guid userId, string name, string coverPath)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(artist);
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artist.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverPath));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,207 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist;
/// <summary>
/// Contains security tests for the <see cref="RestoreArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreArtistEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreArtistEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task RestoreArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore";
// Act
HttpResponseMessage response = await _client.PostAsync(url, null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task RestoreArtist_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task RestoreArtist_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task RestoreArtist_WhenArtistBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(Guid libraryId, Guid artistId) = await SeedLibraryAndDeletedArtistAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
Assert.NotNull(artist);
Assert.True(artist!.IsDeleted);
}
[Fact]
public async Task RestoreArtist_WhenArtistIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
Guid ownLibraryId = await SeedLibraryAsync(actingUserId);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimArtistId) = await SeedLibraryAndDeletedArtistAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ArtistEntity? victimArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId);
Assert.NotNull(victimArtist);
Assert.True(victimArtist!.IsDeleted);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Acting Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with a deleted artist.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndDeletedArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Victim Artist", includeAlbums: false, includeContributors: false);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(artist);
await dbContext.SaveChangesAsync();
return (libraryId, artist.Id);
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,166 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks;
/// <summary>
/// Contains security tests for the <see cref="GetDeletedTracksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedTracksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedTracksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedTracksEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetDeletedTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/deleted-items";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task GetDeletedTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/tracks/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetDeletedTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedTrack()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
const string TITLE = "Secret Deleted Track";
const string PATH = "/private/secret-deleted-track.flac";
Guid libraryId = await SeedLibraryAndDeletedTrackAsync(victimUserId, TITLE, PATH);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/tracks/deleted-items");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain(TITLE, content, StringComparison.Ordinal);
Assert.DoesNotContain(PATH, content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with a deleted track, its album and its artist.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the deleted track.</param>
/// <param name="path">The file system path of the deleted track.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAndDeletedTrackAsync(Guid userId, string title, string path)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(
albumId: albumId,
libraryId: libraryId,
path: path,
title: title,
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: "Victim Album",
tracks: [track],
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,271 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack;
/// <summary>
/// Contains security tests for the <see cref="RestoreTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreTrackEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreTrackEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task RestoreTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore";
// Act
HttpResponseMessage response = await _client.PostAsync(url, null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task RestoreTrack_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task RestoreTrack_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task RestoreTrack_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
public async Task RestoreTrack_WithSQLInjectionInTrackId_ShouldNotCorruptOrLeakData(string maliciousTrackId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Fact]
public async Task RestoreTrack_WhenTrackBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndDeletedTrackAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId);
Assert.NotNull(track);
Assert.True(track!.IsDeleted);
}
[Fact]
public async Task RestoreTrack_WhenTrackIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
Guid ownLibraryId = await SeedLibraryAsync(actingUserId);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimArtistId, Guid victimAlbumId, Guid victimTrackId) = await SeedLibraryArtistAlbumAndDeletedTrackAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/tracks/{victimTrackId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
TrackEntity? victimTrack = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == victimTrackId);
Assert.NotNull(victimTrack);
Assert.True(victimTrack!.IsDeleted);
}
/// <summary>
/// Asserts that a route parameter carrying an injection payload is rejected as a validation error, without leaking internal details.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private async Task AssertRejectedInjectionAttemptAsync(HttpResponseMessage response)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Acting Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist, an album and a deleted 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)> SeedLibraryArtistAlbumAndDeletedTrackAsync(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();
TrackEntity track = _trackEntityFixture.Create(
albumId: albumId,
libraryId: libraryId,
path: $"/music/victim/{Guid.NewGuid():N}.flac",
title: "Victim Track",
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: "Victim Album",
tracks: [track],
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, album.Id, track.Id);
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,139 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
/// <summary>
/// Contains security tests for the <see cref="RestoreMusicAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicAlbumEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicAlbumEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public RestoreMusicAlbumEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task RestoreMusicAlbum_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverRestoreAnotherAlbum(string maliciousId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
string normalizedId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, maliciousId, libraryId.ToString());
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task RestoreMusicAlbum_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
string normalizedId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId.ToString(), albumId.ToString(), maliciousLibraryId);
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
}
[Fact]
public async Task RestoreMusicAlbum_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
_apiFactory.ApiClientStub.Reset();
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
[Fact]
public async Task RestoreMusicAlbum_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
/// <summary>
/// Builds the restore request for the album identified by the route, with the owning library passed through the query string.
/// </summary>
/// <param name="artistId">The raw route value of the artist Id.</param>
/// <param name="albumId">The raw route value of the album Id.</param>
/// <param name="libraryId">The raw query value of the library Id.</param>
/// <returns>The configured restore request.</returns>
private static HttpRequestMessage CreateRestoreRequest(string artistId, string albumId, string libraryId)
{
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/albums/{Uri.EscapeDataString(albumId)}/api-restore-album?libraryId={Uri.EscapeDataString(libraryId)}")
{
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return restoreRequest;
}
}
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
/// <summary>
/// Contains security tests for the <see cref="RestoreMusicArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicArtistEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public RestoreMusicArtistEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task RestoreMusicArtist_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverRestoreAnotherArtist(string maliciousId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
string normalizedId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{libraryId}/artists/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, libraryId.ToString());
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains($"libraries/{libraryId}/artists/{normalizedId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task RestoreMusicArtist_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid artistId = Guid.NewGuid();
string normalizedId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{normalizedId}/artists/{artistId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId.ToString(), maliciousLibraryId);
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains($"libraries/{normalizedId}/artists/{artistId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
}
[Fact]
public async Task RestoreMusicArtist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
_apiFactory.ApiClientStub.Reset();
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
[Fact]
public async Task RestoreMusicArtist_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
/// <summary>
/// Builds the restore request for the artist identified by the route, with the owning library passed through the query string.
/// </summary>
/// <param name="artistId">The raw route value of the artist Id.</param>
/// <param name="libraryId">The raw query value of the library Id.</param>
/// <returns>The configured restore request.</returns>
private static HttpRequestMessage CreateRestoreRequest(string artistId, string libraryId)
{
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/api-restore-artist?libraryId={Uri.EscapeDataString(libraryId)}")
{
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return restoreRequest;
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
/// <summary>
/// Contains security tests for the <see cref="DeletedMusicItemsViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedMusicItemsViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="DeletedMusicItemsViewEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public DeletedMusicItemsViewEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task DeletedMusicItemsView_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Theory]
[InlineData("'; DROP TABLE Libraries; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task DeletedMusicItemsView_WithSQLInjectionInLibraryQueryId_ShouldNeverForwardTheMaliciousIdToTheApi(string maliciousLibraryId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/audio-library/music-library/deleted-items?libraryId={Uri.EscapeDataString(maliciousLibraryId)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousLibraryId, string.Join(",", _apiFactory.ApiClientStub.GetEndpointsCalled), StringComparison.Ordinal);
}
}
@@ -0,0 +1,141 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
/// <summary>
/// Contains security tests for the <see cref="RestoreMusicTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicTrackEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public RestoreMusicTrackEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task RestoreMusicTrack_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverRestoreAnotherTrack(string maliciousId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
string normalizedId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, maliciousId, maliciousId, libraryId.ToString());
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains($"libraries/{libraryId}/artists/{normalizedId}/albums/{normalizedId}/tracks/{normalizedId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task RestoreMusicTrack_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
string normalizedId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), maliciousLibraryId);
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains($"libraries/{normalizedId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(postRequest => postRequest.Endpoint));
}
[Fact]
public async Task RestoreMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
_apiFactory.ApiClientStub.Reset();
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
[Fact]
public async Task RestoreMusicTrack_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
/// <summary>
/// Builds the restore request for the track identified by the route, with the owning library passed through the query string.
/// </summary>
/// <param name="artistId">The raw route value of the artist Id.</param>
/// <param name="albumId">The raw route value of the album Id.</param>
/// <param name="trackId">The raw route value of the track Id.</param>
/// <param name="libraryId">The raw query value of the library Id.</param>
/// <returns>The configured restore request.</returns>
private static HttpRequestMessage CreateRestoreRequest(string artistId, string albumId, string trackId, string libraryId)
{
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/albums/{Uri.EscapeDataString(albumId)}/tracks/{Uri.EscapeDataString(trackId)}/api-restore-track?libraryId={Uri.EscapeDataString(libraryId)}")
{
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return restoreRequest;
}
}
@@ -9,14 +9,12 @@ 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;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
@@ -35,8 +33,8 @@ public class DeleteAlbumCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<DeleteAlbumCommand> _mockValidator;
@@ -54,42 +52,41 @@ public class DeleteAlbumCommandHandlerTests
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_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, the artwork cleanup succeeds and saving changes succeeds.
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist, the library
// and the album exist, marking the album as deleted 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);
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(_artistEntityFixture.Create(includeAlbums: false, includeContributors: false)));
_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>())
_mockAlbumRepository.SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new DeleteAlbumCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
_sut = new DeleteAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenAlbumExists_ShouldRemoveAlbumFromArtistAndReturnDeleted()
public async Task HandleAsync_WhenAlbumExists_ShouldSoftDeleteAlbumAndReturnDeleted()
{
// Arrange
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
ArtistEntity artist = CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid());
StubExistingArtist(artist);
(Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId, albumId, Guid.NewGuid());
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -97,30 +94,51 @@ 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 &&
updatedArtist.Albums.Count == 1 &&
updatedArtist.Albums.All(album => album.Id != albumId)),
Arg.Any<CancellationToken>());
// The album is only marked as deleted, so its metadata, artwork and track paths stay available for a later restore.
await _mockAlbumRepository.Received(1).SoftDeleteByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldLoadTheArtistAggregateAndTheLibraryWithoutTracking()
{
// Arrange
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId, albumId, Guid.NewGuid());
// Act
await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// The album is a child of the artist aggregate, so it is loaded with the aggregate and not with a separate album read.
await _mockArtistRepository.Received(1).GetByIdAsync(
artistId,
shouldIncludeNavigationProperties: true,
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>());
await _mockLibraryRepository.Received(1).GetByIdAsync(
libraryId,
shouldIncludeNavigationProperties: true,
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(
Arg.Any<Guid>(),
Arg.Any<bool>(),
Arg.Any<bool>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
// Arrange
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
_mockValidator.Validate(Arg.Any<DeleteAlbumCommand>()).Returns([DomainErrors.Music.AlbumIdCannotBeEmpty]);
_mockValidator.Validate(Arg.Any<DeleteAlbumCommand>())
.Returns([DomainErrors.Music.AlbumIdCannotBeEmpty]);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -129,8 +147,8 @@ 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 _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -148,7 +166,9 @@ public class DeleteAlbumCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
@@ -165,7 +185,7 @@ public class DeleteAlbumCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -192,10 +212,10 @@ public class DeleteAlbumCommandHandlerTests
{
// Arrange
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
ArtistEntity artist = CreateArtistWithAlbums(Guid.NewGuid(), artistId, albumId, Guid.NewGuid());
StubExistingArtist(artist);
(_, Guid artistId, _) = GetCommandIds(command);
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -213,10 +233,8 @@ public class DeleteAlbumCommandHandlerTests
{
// 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()));
(Guid libraryId, Guid artistId, _) = GetCommandIds(command);
StubArtist(libraryId, artistId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
@@ -229,26 +247,7 @@ public class DeleteAlbumCommandHandlerTests
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), 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_WhenAlbumDoesNotExistInArtist_ShouldReturnAlbumNotFoundError()
{
// Arrange
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, Guid.NewGuid(), Guid.NewGuid()));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -257,10 +256,8 @@ public class DeleteAlbumCommandHandlerTests
{
// 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()));
(Guid libraryId, Guid artistId, _) = GetCommandIds(command);
StubArtist(libraryId, artistId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
@@ -270,7 +267,8 @@ public class DeleteAlbumCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
@@ -278,10 +276,8 @@ public class DeleteAlbumCommandHandlerTests
{
// 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()));
(Guid libraryId, Guid artistId, _) = GetCommandIds(command);
StubArtist(libraryId, artistId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(null));
@@ -291,44 +287,39 @@ public class DeleteAlbumCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistDomainConversionFails_ShouldReturnError()
public async Task HandleAsync_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnArtistMustHaveAtLeastOneAlbumWithoutDeleting()
{
// Arrange
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
AlbumEntity firstAlbum = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false);
AlbumEntity secondAlbum = _albumEntityFixture.Create(id: Guid.NewGuid(), artistId: artistId, libraryId: libraryId, includeTracks: false);
// An empty name is rejected by the artist aggregate invariant, so the repository entity fails to convert to a domain entity.
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: string.Empty, albums: [firstAlbum, secondAlbum]);
StubExistingArtist(artist);
(Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId, albumId);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// The domain rejects the last album before the write is reached.
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistNameCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
Assert.Equal(DomainErrors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError);
await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRemovingTheLastAlbumOfTheArtistFails_ShouldReturnErrorWithoutSaving()
public async Task HandleAsync_WhenTheLastAlbumCheckRacesWithAnotherDelete_ShouldReturnTheStorageFallbackError()
{
// Arrange
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
// The artist owns a single album, which the aggregate forbids removing.
ArtistEntity artist = CreateArtistWithAlbums(libraryId, artistId, albumId);
StubExistingArtist(artist);
(Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId, albumId, Guid.NewGuid());
// The aggregate still sees a sibling album, but the storage write finds that the sibling was deleted by a concurrent request.
_mockAlbumRepository.SoftDeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(DomainErrors.Music.ArtistMustHaveAtLeastOneAlbum);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -336,44 +327,56 @@ 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 _mockAlbumRepository.Received(1).SoftDeleteByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutUpdatingTheArtist()
public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError()
{
// 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);
(Guid libraryId, Guid artistId, _) = GetCommandIds(command);
// The artist owns an album, but not the requested one, so the aggregate graph does not contain it.
StubArtistAndLibrary(libraryId, artistId, Guid.NewGuid());
// 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>());
Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError);
await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving()
public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundError()
{
// 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()));
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
(Guid libraryId, Guid artistId, _) = GetCommandIds(command);
// The route artist owns a different album, and the requested album belongs to another artist, so the aggregate graph does not contain it.
StubArtistAndLibrary(libraryId, artistId, Guid.NewGuid());
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError);
await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSoftDeleteFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId, albumId, Guid.NewGuid());
_mockAlbumRepository.SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
@@ -382,6 +385,7 @@ public class DeleteAlbumCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockAlbumRepository.Received(1).SoftDeleteByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -390,10 +394,8 @@ public class DeleteAlbumCommandHandlerTests
{
// 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()));
(Guid libraryId, Guid artistId, Guid albumId) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId, albumId, Guid.NewGuid());
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
@@ -403,29 +405,48 @@ public class DeleteAlbumCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.Received(1).SoftDeleteByIdAsync(albumId, Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates an artist that owns the provided albums.
/// Extracts the parsed identifiers carried by <paramref name="command"/>.
/// </summary>
/// <param name="command">The command whose route identifiers are extracted.</param>
/// <returns>The parsed library, artist and album identifiers.</returns>
private static (Guid libraryId, Guid artistId, Guid albumId) GetCommandIds(DeleteAlbumCommand command)
{
return (
Guid.Parse(command.LibraryId!),
Guid.Parse(command.ArtistId!),
Guid.Parse(command.AlbumId!));
}
/// <summary>
/// Stubs the artist repository so that the handler finds an artist that belongs to <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
/// <param name="albumIds">The Ids of the albums the artist owns.</param>
/// <returns>The created artist entity.</returns>
private ArtistEntity CreateArtistWithAlbums(Guid libraryId, Guid artistId, params Guid[] albumIds)
/// <param name="ownedAlbumIds">The Ids of the albums the artist owns.</param>
private ArtistEntity StubArtist(Guid libraryId, Guid artistId, params Guid[] ownedAlbumIds)
{
List<AlbumEntity> albums = [.. albumIds.Select(albumId => _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: true))];
return _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: albums, includeContributors: true);
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false);
artist.Albums = [.. ownedAlbumIds.Select(albumId => _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false))];
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
return artist;
}
/// <summary>
/// Stubs the artist repository so that the artist read returns <paramref name="artist"/>.
/// Stubs the artist and library repositories so that the handler finds the artist, its albums and its library.
/// </summary>
/// <param name="artist">The artist returned by the artist repository.</param>
private void StubExistingArtist(ArtistEntity artist)
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
/// <param name="ownedAlbumIds">The Ids of the albums the artist owns.</param>
private void StubArtistAndLibrary(Guid libraryId, Guid artistId, params Guid[] ownedAlbumIds)
{
_mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
StubArtist(libraryId, artistId, ownedAlbumIds);
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId);
_mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any<bool>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
}
}
@@ -0,0 +1,299 @@
#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.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.Albums.Commands.RestoreAlbum;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
/// <summary>
/// Contains unit tests for the <see cref="RestoreAlbumCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreAlbumCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<RestoreAlbumCommand> _mockValidator;
private readonly RestoreAlbumCommandHandler _sut;
private readonly Guid _userId;
private readonly RestoreAlbumCommandFixture _restoreAlbumCommandFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreAlbumCommandHandlerTests"/> class.
/// </summary>
public RestoreAlbumCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<RestoreAlbumCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the restoration, restoring the deleted
// album succeeds, and saving changes succeeds.
_mockValidator.Validate(Arg.Any<RestoreAlbumCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockAlbumRepository.RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new RestoreAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenDeletedAlbumExists_ShouldRestoreAlbumAndReturnUpdated()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false));
_mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await _mockAlbumRepository.Received(1).RestoreSoftDeletedByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
_mockValidator.Validate(Arg.Any<RestoreAlbumCommand>())
.Returns([DomainErrors.Music.AlbumIdCannotBeEmpty]);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.AlbumIdCannotBeEmpty, result.FirstError);
await _mockAlbumRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAlbumRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutRestoring()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
_mockAlbumRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletedAlbumDoesNotExist_ShouldReturnAlbumNotFoundError()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
_mockAlbumRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<AlbumEntity?>(null));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: Guid.NewGuid(), includeTracks: false));
_mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the album exists in another library.
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid albumId = Guid.Parse(command.AlbumId!);
AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId, includeTracks: false));
_mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the album exists under another artist.
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false));
_mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRestoreFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false));
_mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockAlbumRepository.RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockAlbumRepository.Received(1).RestoreSoftDeletedByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
Guid albumId = Guid.Parse(command.AlbumId!);
AlbumEntity album = MarkAsDeleted(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false));
_mockAlbumRepository.GetSoftDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockAlbumRepository.Received(1).RestoreSoftDeletedByIdAsync(albumId, Arg.Any<CancellationToken>());
}
/// <summary>
/// Marks <paramref name="album"/> as soft deleted, the way the album repository returns it to the restore handler.
/// </summary>
/// <param name="album">The album to mark as soft deleted.</param>
/// <returns>The same <paramref name="album"/> instance, marked as soft deleted.</returns>
private static AlbumEntity MarkAsDeleted(AlbumEntity album)
{
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow;
return album;
}
}
@@ -0,0 +1,128 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
/// <summary>
/// Contains unit tests for the <see cref="RestoreAlbumCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreAlbumCommandValidatorTests
{
private readonly RestoreAlbumCommandFixture _restoreAlbumCommandFixture = new();
private readonly RestoreAlbumCommandValidator _validator = new();
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-an-artist-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId)
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-an-album-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId)
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(albumId: albumId, includeAlbumId: albumId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(artistId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create(albumId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
RestoreAlbumCommand command = _restoreAlbumCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -89,12 +89,14 @@ public class UpdateAlbumCoverCommandHandlerTests
_mockPathService.PathSeparator.Returns('/');
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo => PathSegment.Create(callInfo.Arg<string>(), isDirectory: true, isDrive: false));
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => PathSegment.Create($"{callInfo.ArgAt<string>(0)}-{callInfo.ArgAt<string>(1)}", isDirectory: true, isDrive: false));
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
_mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockMusicArtworkService.SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(STORED_COVER_PATH));
_mockMusicArtworkService.DeleteStoredArtwork(Arg.Any<string>()).Returns(Result.From(Result.Deleted));
@@ -119,7 +121,7 @@ public class UpdateAlbumCoverCommandHandlerTests
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -137,7 +139,7 @@ public class UpdateAlbumCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -156,7 +158,7 @@ public class UpdateAlbumCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -195,7 +197,7 @@ public class UpdateAlbumCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -216,7 +218,7 @@ public class UpdateAlbumCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -236,7 +238,7 @@ public class UpdateAlbumCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -256,7 +258,7 @@ public class UpdateAlbumCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -275,7 +277,7 @@ public class UpdateAlbumCoverCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -296,7 +298,7 @@ public class UpdateAlbumCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -316,7 +318,7 @@ public class UpdateAlbumCoverCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), string.Empty, Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), string.Empty, Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
@@ -337,7 +339,7 @@ public class UpdateAlbumCoverCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -351,7 +353,7 @@ public class UpdateAlbumCoverCommandHandlerTests
SetupExistingLibrary(command);
SetupExistingArtist(command);
_mockMusicArtworkService.SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Errors.FileSystemManagement.FileTooLarge);
@@ -382,7 +384,7 @@ public class UpdateAlbumCoverCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), "Ep", Arg.Any<CancellationToken>());
}
@@ -392,11 +394,11 @@ public class UpdateAlbumCoverCommandHandlerTests
// Arrange
UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
// The artist is named "Live", which is also a release type name, but the album uses no release type, so the segment right before the album
// directory is the artist directory and must not be mistaken for a release type directory.
SetupExistingAlbum(command, includeReleaseType: false);
// directory is the artist directory ({artistName}-{artistId}) and must not be mistaken for a release type directory.
AlbumEntity existingAlbum = SetupExistingAlbum(command, includeReleaseType: false);
SetupExistingLibrary(command);
SetupExistingArtist(command, name: "Live");
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: "/media/music/library/Live/album/cover.jpg"));
SetupExistingArtwork(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, artworkType: ArtworkType.Cover, fileName: $"/media/music/library/Live-{existingAlbum.ArtistId}/album/cover.jpg"));
// Act
Result<UpdateAlbumCoverResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -404,7 +406,7 @@ public class UpdateAlbumCoverCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), "Live", Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), "Live", Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Is<string?>(releaseTypeName => releaseTypeName == null), Arg.Any<CancellationToken>());
}
@@ -425,7 +427,7 @@ public class UpdateAlbumCoverCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), "Album", Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), "Album", Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), "Ep", Arg.Any<CancellationToken>());
}
@@ -445,7 +447,7 @@ public class UpdateAlbumCoverCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), "Single", Arg.Any<CancellationToken>());
}
@@ -466,7 +468,7 @@ public class UpdateAlbumCoverCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), "Single", Arg.Any<CancellationToken>());
}
@@ -485,7 +487,7 @@ public class UpdateAlbumCoverCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), "Single", Arg.Any<CancellationToken>());
}
@@ -504,7 +506,7 @@ public class UpdateAlbumCoverCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Is<string?>(releaseTypeName => releaseTypeName == null), Arg.Any<CancellationToken>());
}
@@ -649,6 +651,7 @@ public class UpdateAlbumCoverCommandHandlerTests
existingAlbum.LibraryId,
existingAlbum.Id,
library.Title,
existingAlbum.ArtistId,
artist.Name,
existingAlbum.Title,
Arg.Any<Stream>(),
@@ -0,0 +1,238 @@
#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.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.Albums.Queries.GetDeletedAlbums;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedAlbumsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedAlbumsQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetDeletedAlbumsQuery> _mockValidator;
private readonly GetDeletedAlbumsQueryHandler _sut;
private readonly Guid _userId;
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly GetDeletedAlbumsQueryFixture _getDeletedAlbumsQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedAlbumsQueryHandlerTests"/> class.
/// </summary>
public GetDeletedAlbumsQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetDeletedAlbumsQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the query is valid, the current user is authenticated, the library ownership policy allows access, there are no deleted
// albums and none of them has stored artwork.
_mockValidator.Validate(Arg.Any<GetDeletedAlbumsQuery>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockAlbumRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([]));
_mockMusicArtworkRepository.GetByOwnersAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
_sut = new GetDeletedAlbumsQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenDeletedAlbumsExist_ShouldReturnTheirMappedResponsesWithCoverPaths()
{
// Arrange
GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
string coverFileName = $"covers/{Guid.NewGuid()}.jpg";
DateTime firstDeletedOnUtc = new(2026, 2, 20, 18, 45, 0, DateTimeKind.Utc);
AlbumEntity firstAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false);
firstAlbum.IsDeleted = true;
firstAlbum.DeletedOnUtc = firstDeletedOnUtc;
firstAlbum.Artist = _artistEntityFixture.Create(id: firstAlbum.ArtistId, libraryId: libraryId, includeAlbums: false, includeContributors: false);
// A deleted album without a recorded deletion time falls back to its creation time, so the history never shows a default date.
AlbumEntity secondAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false);
secondAlbum.IsDeleted = true;
secondAlbum.DeletedOnUtc = null;
secondAlbum.Artist = _artistEntityFixture.Create(id: secondAlbum.ArtistId, libraryId: libraryId, includeAlbums: false, includeContributors: false);
_mockAlbumRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([firstAlbum, secondAlbum]));
_mockMusicArtworkRepository.GetByOwnersAsync(MusicArtworkOwnerType.Album, Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>(
[
// A cover row whose stored file is not resolved yet is skipped, so it cannot hide the resolved cover of the same album.
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: firstAlbum.Id, artworkType: ArtworkType.Cover, ordinal: 1, includeFileName: false),
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: firstAlbum.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverFileName),
// Non cover artwork is not used as the cover of the deleted album.
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: firstAlbum.Id, artworkType: ArtworkType.Booklet, ordinal: 0)
]));
// Act
Result<IReadOnlyList<DeletedAlbumResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(firstAlbum.Id, result.Value[0].Id);
Assert.Equal(firstAlbum.LibraryId, result.Value[0].LibraryId);
Assert.Equal(firstAlbum.ArtistId, result.Value[0].ArtistId);
Assert.Equal(firstAlbum.Artist.Name, result.Value[0].ArtistName);
Assert.Equal(firstAlbum.Title, result.Value[0].Title);
Assert.Equal(firstDeletedOnUtc, result.Value[0].DeletedOnUtc);
Assert.Equal(coverFileName, result.Value[0].CoverPath);
Assert.Equal(secondAlbum.Id, result.Value[1].Id);
Assert.Equal(secondAlbum.Artist.Name, result.Value[1].ArtistName);
Assert.Equal(secondAlbum.CreatedOnUtc, result.Value[1].DeletedOnUtc);
Assert.Null(result.Value[1].CoverPath);
await _mockMusicArtworkRepository.Received(1).GetByOwnersAsync(
MusicArtworkOwnerType.Album,
Arg.Is<IReadOnlyCollection<Guid>>(ownerIds => ownerIds.Count == 2 && ownerIds.Contains(firstAlbum.Id) && ownerIds.Contains(secondAlbum.Id)),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThereAreNoDeletedAlbums_ShouldReturnAnEmptyCollection()
{
// Arrange
GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create();
// Act
Result<IReadOnlyList<DeletedAlbumResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
// Arrange
GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetDeletedAlbumsQuery>())
.Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]);
// Act
Result<IReadOnlyList<DeletedAlbumResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockAlbumRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<DeletedAlbumResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAlbumRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<IReadOnlyList<DeletedAlbumResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResult()
{
// Arrange
GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create();
_mockAlbumRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<IReadOnlyList<DeletedAlbumResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkRepositoryFails_ShouldReturnFailureResult()
{
// Arrange
GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow;
_mockAlbumRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
_mockMusicArtworkRepository.GetByOwnersAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<IReadOnlyList<DeletedAlbumResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedAlbumsQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedAlbumsQueryValidatorTests
{
private readonly GetDeletedAlbumsQueryFixture _getDeletedAlbumsQueryFixture = new();
private readonly GetDeletedAlbumsQueryValidator _validator = new();
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
{
// Arrange
GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetDeletedAlbumsQuery query = _getDeletedAlbumsQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -9,7 +9,6 @@ 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;
@@ -34,7 +33,6 @@ 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;
@@ -54,31 +52,31 @@ 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, the artwork cleanup succeeds and saving changes succeeds.
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist and the
// library exist, marking the artist as deleted 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);
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(_artistEntityFixture.Create(includeAlbums: false, includeContributors: false)));
_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);
_mockArtistRepository.SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new DeleteArtistCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
_sut = new DeleteArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenArtistExists_ShouldDeleteArtistAndReturnDeleted()
public async Task HandleAsync_WhenArtistExists_ShouldSoftDeleteArtistAndReturnDeleted()
{
// Arrange
DeleteArtistCommand command = _deleteArtistCommandFixture.Create();
@@ -87,6 +85,8 @@ public class DeleteArtistCommandHandlerTests
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));
_mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any<bool>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: libraryId)));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -94,19 +94,43 @@ 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>());
// The artist is only marked as deleted, so its metadata, artwork and paths stay available for a later restore.
await _mockArtistRepository.Received(1).SoftDeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldLoadTheArtistAndTheLibraryWithoutNavigationPropertiesOrTracking()
{
// 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));
_mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any<bool>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: libraryId)));
// Act
await _sut.HandleAsync(command, CancellationToken.None);
// Assert
await _mockArtistRepository.Received(1).GetByIdAsync(
artistId,
shouldIncludeNavigationProperties: false,
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>());
await _mockLibraryRepository.Received(1).GetByIdAsync(
libraryId,
shouldIncludeNavigationProperties: true,
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
@@ -122,8 +146,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 _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -141,7 +164,9 @@ public class DeleteArtistCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
@@ -158,7 +183,7 @@ public class DeleteArtistCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -177,6 +202,7 @@ public class DeleteArtistCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -198,6 +224,7 @@ public class DeleteArtistCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -223,7 +250,7 @@ public class DeleteArtistCommandHandlerTests
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -246,7 +273,8 @@ public class DeleteArtistCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
@@ -268,12 +296,12 @@ public class DeleteArtistCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutDeletingTheArtist()
public async Task HandleAsync_WhenSoftDeleteFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
DeleteArtistCommand command = _deleteArtistCommandFixture.Create();
@@ -282,31 +310,9 @@ public class DeleteArtistCommandHandlerTests
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()
{
// 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));
_mockArtistRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any<bool>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: libraryId)));
_mockArtistRepository.SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
@@ -315,7 +321,7 @@ public class DeleteArtistCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).SoftDeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -329,6 +335,8 @@ public class DeleteArtistCommandHandlerTests
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));
_mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any<bool>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: libraryId)));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
@@ -338,6 +346,6 @@ public class DeleteArtistCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).SoftDeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
}
}
@@ -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.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.Artists.Commands.RestoreArtist;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
/// <summary>
/// Contains unit tests for the <see cref="RestoreArtistCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreArtistCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<RestoreArtistCommand> _mockValidator;
private readonly RestoreArtistCommandHandler _sut;
private readonly Guid _userId;
private readonly RestoreArtistCommandFixture _restoreArtistCommandFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreArtistCommandHandlerTests"/> class.
/// </summary>
public RestoreArtistCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<RestoreArtistCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the restoration, restoring the deleted
// artist succeeds, no visible artist took over its name, and saving changes succeeds.
_mockValidator.Validate(Arg.Any<RestoreArtistCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockArtistRepository.GetByNameAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(null));
_mockArtistRepository.RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new RestoreArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenDeletedArtistExists_ShouldRestoreArtistAndReturnUpdated()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false));
_mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await _mockArtistRepository.Received(1).RestoreSoftDeletedByIdAsync(artistId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).GetByNameAsync(libraryId, artist.Name, Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
_mockValidator.Validate(Arg.Any<RestoreArtistCommand>())
.Returns([DomainErrors.Music.ArtistIdCannotBeEmpty]);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistIdCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutRestoring()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
_mockArtistRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletedArtistDoesNotExist_ShouldReturnArtistNotFoundError()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
_mockArtistRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(null));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
Guid artistId = Guid.Parse(command.ArtistId!);
ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false));
_mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the artist exists in another library.
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetByNameAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false));
_mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetByNameAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenVisibleArtistTookOverTheName_ShouldReturnArtistAlreadyExistsError()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false));
ArtistEntity artistWithSameName = _artistEntityFixture.Create(libraryId: libraryId, name: artist.Name, includeAlbums: false, includeContributors: false);
_mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockArtistRepository.GetByNameAsync(libraryId, artist.Name, Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artistWithSameName));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// The name of a visible artist is unique within a library, so the deleted artist cannot be restored until it is renamed.
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistAlreadyExists, result.FirstError);
await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetArtistByNameFails_ShouldReturnFailureResultWithoutRestoring()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false));
_mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockArtistRepository.GetByNameAsync(libraryId, artist.Name, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRestoreFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false));
_mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockArtistRepository.RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.Received(1).RestoreSoftDeletedByIdAsync(artistId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
Guid libraryId = Guid.Parse(command.LibraryId!);
Guid artistId = Guid.Parse(command.ArtistId!);
ArtistEntity artist = MarkAsDeleted(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false));
_mockArtistRepository.GetSoftDeletedByIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockArtistRepository.Received(1).RestoreSoftDeletedByIdAsync(artistId, Arg.Any<CancellationToken>());
}
/// <summary>
/// Marks <paramref name="artist"/> as soft deleted, the way the artist repository returns it to the restore handler.
/// </summary>
/// <param name="artist">The artist to mark as soft deleted.</param>
/// <returns>The same <paramref name="artist"/> instance, marked as soft deleted.</returns>
private static ArtistEntity MarkAsDeleted(ArtistEntity artist)
{
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow;
return artist;
}
}
@@ -0,0 +1,97 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
/// <summary>
/// Contains unit tests for the <see cref="RestoreArtistCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreArtistCommandValidatorTests
{
private readonly RestoreArtistCommandFixture _restoreArtistCommandFixture = new();
private readonly RestoreArtistCommandValidator _validator = new();
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-an-artist-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId)
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create(artistId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
RestoreArtistCommand command = _restoreArtistCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -82,7 +82,7 @@ public class UpdateArtistCoverCommandHandlerTests
_mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockMusicArtworkService.SaveArtistArtworkAsync(
Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.From(STORED_COVER_PATH));
_mockMusicArtworkService.DeleteStoredArtwork(Arg.Any<string>()).Returns(Result.From(Result.Deleted));
@@ -106,7 +106,7 @@ public class UpdateArtistCoverCommandHandlerTests
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -124,7 +124,7 @@ public class UpdateArtistCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -143,7 +143,7 @@ public class UpdateArtistCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -182,7 +182,7 @@ public class UpdateArtistCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -202,7 +202,7 @@ public class UpdateArtistCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -222,7 +222,7 @@ public class UpdateArtistCoverCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -241,7 +241,7 @@ public class UpdateArtistCoverCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -261,7 +261,7 @@ public class UpdateArtistCoverCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().UpsertCoverAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -274,7 +274,7 @@ public class UpdateArtistCoverCommandHandlerTests
SetupExistingArtist(command);
SetupExistingLibrary(command);
_mockMusicArtworkService.SaveArtistArtworkAsync(
Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(),
Arg.Any<Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Errors.FileSystemManagement.FileTooLarge);
@@ -421,6 +421,7 @@ public class UpdateArtistCoverCommandHandlerTests
await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync(
existingArtist.LibraryId,
library.Title,
existingArtist.Id,
existingArtist.Name,
Arg.Any<Stream>(),
command.FileName!,
@@ -0,0 +1,232 @@
#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.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.Artists.Queries.GetDeletedArtists;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedArtistsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedArtistsQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetDeletedArtistsQuery> _mockValidator;
private readonly GetDeletedArtistsQueryHandler _sut;
private readonly Guid _userId;
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly GetDeletedArtistsQueryFixture _getDeletedArtistsQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedArtistsQueryHandlerTests"/> class.
/// </summary>
public GetDeletedArtistsQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetDeletedArtistsQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the query is valid, the current user is authenticated, the library ownership policy allows access, there are no deleted
// artists and none of them has stored artwork.
_mockValidator.Validate(Arg.Any<GetDeletedArtistsQuery>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockArtistRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<ArtistEntity>>([]));
_mockMusicArtworkRepository.GetByOwnersAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
_sut = new GetDeletedArtistsQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenDeletedArtistsExist_ShouldReturnTheirMappedResponsesWithCoverPaths()
{
// Arrange
GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
string coverFileName = $"covers/{Guid.NewGuid()}.jpg";
DateTime firstDeletedOnUtc = new(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc);
ArtistEntity firstArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
firstArtist.IsDeleted = true;
firstArtist.DeletedOnUtc = firstDeletedOnUtc;
// A deleted artist without a recorded deletion time falls back to its creation time, so the history never shows a default date.
ArtistEntity secondArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
secondArtist.IsDeleted = true;
secondArtist.DeletedOnUtc = null;
_mockArtistRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<ArtistEntity>>([firstArtist, secondArtist]));
_mockMusicArtworkRepository.GetByOwnersAsync(MusicArtworkOwnerType.Artist, Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>(
[
// A cover row whose stored file is not resolved yet is skipped, so it cannot hide the resolved cover of the same artist.
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: firstArtist.Id, artworkType: ArtworkType.Cover, ordinal: 1, includeFileName: false),
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: firstArtist.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverFileName),
// Non cover artwork is not used as the cover of the deleted artist.
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: firstArtist.Id, artworkType: ArtworkType.Back, ordinal: 0)
]));
// Act
Result<IReadOnlyList<DeletedArtistResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(firstArtist.Id, result.Value[0].Id);
Assert.Equal(firstArtist.LibraryId, result.Value[0].LibraryId);
Assert.Equal(firstArtist.Name, result.Value[0].Name);
Assert.Equal(firstDeletedOnUtc, result.Value[0].DeletedOnUtc);
Assert.Equal(coverFileName, result.Value[0].CoverPath);
Assert.Equal(secondArtist.Id, result.Value[1].Id);
Assert.Equal(secondArtist.CreatedOnUtc, result.Value[1].DeletedOnUtc);
Assert.Null(result.Value[1].CoverPath);
await _mockMusicArtworkRepository.Received(1).GetByOwnersAsync(
MusicArtworkOwnerType.Artist,
Arg.Is<IReadOnlyCollection<Guid>>(ownerIds => ownerIds.Count == 2 && ownerIds.Contains(firstArtist.Id) && ownerIds.Contains(secondArtist.Id)),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThereAreNoDeletedArtists_ShouldReturnAnEmptyCollection()
{
// Arrange
GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create();
// Act
Result<IReadOnlyList<DeletedArtistResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
// Arrange
GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetDeletedArtistsQuery>())
.Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]);
// Act
Result<IReadOnlyList<DeletedArtistResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<DeletedArtistResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<IReadOnlyList<DeletedArtistResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResult()
{
// Arrange
GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create();
_mockArtistRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<IReadOnlyList<DeletedArtistResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockMusicArtworkRepository.DidNotReceive().GetByOwnersAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkRepositoryFails_ShouldReturnFailureResult()
{
// Arrange
GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow;
_mockArtistRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<ArtistEntity>>([artist]));
_mockMusicArtworkRepository.GetByOwnersAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<IReadOnlyList<DeletedArtistResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedArtistsQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedArtistsQueryValidatorTests
{
private readonly GetDeletedArtistsQueryFixture _getDeletedArtistsQueryFixture = new();
private readonly GetDeletedArtistsQueryValidator _validator = new();
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
{
// Arrange
GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetDeletedArtistsQuery query = _getDeletedArtistsQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -1,324 +0,0 @@
#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,7 +8,6 @@ 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,8 +32,9 @@ public class DeleteTrackCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly ITrackRepository _mockTrackRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMusicArtworkCleanupService _mockMusicArtworkCleanupService;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<DeleteTrackCommand> _mockValidator;
@@ -53,38 +53,51 @@ public class DeleteTrackCommandHandlerTests
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockTrackRepository = Substitute.For<ITrackRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_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, the artwork cleanup succeeds and saving changes succeeds.
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist, the library,
// the album and the track exist, marking the track as deleted 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>())
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(_artistEntityFixture.Create(includeAlbums: false, includeContributors: false)));
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(_libraryEntityFixture.Create()));
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<AlbumEntity?>(_albumEntityFixture.Create(includeTracks: false)));
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<TrackEntity?>(_trackEntityFixture.Create(includeMetadata: false)));
_mockTrackRepository.SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new DeleteTrackCommandHandler(_mockUnitOfWork, _mockMusicArtworkCleanupService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
_sut = new DeleteTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenTrackExists_ShouldRemoveTrackFromAlbumAndReturnDeleted()
public async Task HandleAsync_WhenTrackExists_ShouldSoftDeleteTrackAndReturnDeleted()
{
// 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);
StubArtistAndLibrary(libraryId, artistId);
StubAlbum(libraryId, artistId, albumId);
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false);
_mockTrackRepository.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -92,31 +105,25 @@ 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 &&
updatedArtist.Albums.Count == 1 &&
updatedArtist.Albums[0].Id == albumId &&
updatedArtist.Albums[0].Tracks.Count == 0),
Arg.Any<CancellationToken>());
// The track is only marked as deleted, so its metadata, artwork and path stay available for a later restore.
await _mockTrackRepository.Received(1).SoftDeleteByIdAsync(trackId, Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldLoadTheArtistWithNavigationPropertiesAndTheLibraryWithoutTracking()
public async Task HandleAsync_WhenCalled_ShouldLoadTheScopingRowsWithoutNavigationPropertiesOrTracking()
{
// 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);
StubArtistAndLibrary(libraryId, artistId);
StubAlbum(libraryId, artistId, albumId);
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false);
_mockTrackRepository.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
// Act
await _sut.HandleAsync(command, CancellationToken.None);
@@ -124,17 +131,24 @@ public class DeleteTrackCommandHandlerTests
// Assert
await _mockArtistRepository.Received(1).GetByIdAsync(
artistId,
shouldIncludeNavigationProperties: true,
shouldIncludeNavigationProperties: false,
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>());
await _mockLibraryRepository.Received(1).GetByIdAsync(
libraryId,
shouldIncludeNavigationProperties: true,
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>());
await _mockAlbumRepository.Received(1).GetByIdAsync(
albumId,
shouldIncludeNavigationProperties: false,
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>());
await _mockTrackRepository.Received(1).GetByIdAsync(
trackId,
shouldIncludeNavigationProperties: false,
shouldTrackEntities: false,
cancellationToken: Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId,
Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId),
Arg.Any<CancellationToken>());
}
[Fact]
@@ -153,13 +167,14 @@ 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 _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError()
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
@@ -172,27 +187,26 @@ public class DeleteTrackCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetArtistFails_ShouldReturnError()
public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(_, Guid artistId, _, _) = GetCommandIds(command);
Error error = Error.Failure(description: "Failed to get artist");
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(error);
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -201,9 +215,8 @@ public class DeleteTrackCommandHandlerTests
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(_, Guid artistId, _, _) = GetCommandIds(command);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(null));
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<ArtistEntity?>(null));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -211,18 +224,18 @@ public class DeleteTrackCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundErrorWithoutEvaluatingThePolicy()
public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
ArtistEntity artist = CreateArtistWithAlbumAndTrack(Guid.NewGuid(), artistId, albumId, trackId);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
(_, Guid artistId, _, _) = GetCommandIds(command);
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// Act
@@ -233,7 +246,6 @@ public class DeleteTrackCommandHandlerTests
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -242,10 +254,8 @@ public class DeleteTrackCommandHandlerTests
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
(Guid libraryId, Guid artistId, _, _) = GetCommandIds(command);
StubArtist(libraryId, artistId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
@@ -255,72 +265,30 @@ public class DeleteTrackCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumDoesNotExistInArtist_ShouldReturnAlbumNotFoundError()
public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, _, Guid trackId) = GetCommandIds(command);
Guid otherAlbumId = Guid.NewGuid();
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, otherAlbumId, trackId);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
(Guid libraryId, Guid artistId, _, _) = GetCommandIds(command);
StubArtist(libraryId, artistId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTrackDoesNotExistInAlbum_ShouldReturnTrackNotFoundError()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, _) = GetCommandIds(command);
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, Guid.NewGuid());
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetLibraryFails_ShouldReturnError()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
Error error = Error.Failure(description: "Failed to get library");
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: 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>());
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -329,12 +297,10 @@ public class DeleteTrackCommandHandlerTests
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId);
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
(Guid libraryId, Guid artistId, _, _) = GetCommandIds(command);
StubArtist(libraryId, artistId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<LibraryEntity?>(null));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -342,77 +308,156 @@ public class DeleteTrackCommandHandlerTests
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtistDomainConversionFails_ShouldReturnError()
public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
// An empty name is rejected by the artist aggregate invariant, so the repository entity fails to convert to a domain entity.
AlbumEntity album = CreateAlbumWithTrack(libraryId, artistId, albumId, trackId);
ArtistEntity artist = _artistEntityFixture.Create(
id: artistId,
libraryId: libraryId,
name: string.Empty,
albums: [album],
includeContributors: false,
includeMetadata: false);
StubArtistAndLibrary(artist, libraryId);
(Guid libraryId, Guid artistId, _, _) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId);
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.ArtistNameCannotBeEmpty, result.FirstError);
await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkCleanupFails_ShouldReturnErrorWithoutUpdatingTheArtist()
public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError()
{
// 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);
(Guid libraryId, Guid artistId, _, _) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId);
_mockAlbumRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<AlbumEntity?>(null));
// 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>());
Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError);
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving()
public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundError()
{
// 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 update artist");
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
(Guid libraryId, Guid artistId, Guid albumId, _) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId);
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId, includeTracks: false);
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError);
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTrackRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, _) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId);
StubAlbum(libraryId, artistId, albumId);
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTrackDoesNotExist_ShouldReturnTrackNotFoundError()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, _) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId);
StubAlbum(libraryId, artistId, albumId);
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<TrackEntity?>(null));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTrackBelongsToAnotherAlbum_ShouldReturnTrackNotFoundError()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId);
StubAlbum(libraryId, artistId, albumId);
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: Guid.NewGuid(), libraryId: libraryId, includeMetadata: false);
_mockTrackRepository.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSoftDeleteFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
DeleteTrackCommand command = _deleteTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
StubArtistAndLibrary(libraryId, artistId);
StubAlbum(libraryId, artistId, albumId);
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false);
_mockTrackRepository.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockTrackRepository.SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockTrackRepository.Received(1).SoftDeleteByIdAsync(trackId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -422,19 +467,21 @@ public class DeleteTrackCommandHandlerTests
// 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 save changes");
StubArtistAndLibrary(libraryId, artistId);
StubAlbum(libraryId, artistId, albumId);
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false);
_mockTrackRepository.GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(error);
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockTrackRepository.Received(1).SoftDeleteByIdAsync(trackId, Arg.Any<CancellationToken>());
}
/// <summary>
@@ -452,67 +499,40 @@ public class DeleteTrackCommandHandlerTests
}
/// <summary>
/// Creates an artist that contains a single album, which in turn contains a single track.
/// Stubs the artist repository so that the handler finds an artist that belongs to <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
/// <param name="albumId">The Id of the album.</param>
/// <param name="trackId">The Id of the track.</param>
/// <returns>The created artist entity, with its album and track graph.</returns>
private ArtistEntity CreateArtistWithAlbumAndTrack(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
private void StubArtist(Guid libraryId, Guid artistId)
{
AlbumEntity album = CreateAlbumWithTrack(libraryId, artistId, albumId, trackId);
return _artistEntityFixture.Create(
id: artistId,
libraryId: libraryId,
albums: [album],
includeContributors: false,
includeMetadata: false);
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));
}
/// <summary>
/// Creates an album that contains a single track.
/// Stubs the album repository so that the handler finds an album of <paramref name="artistId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="albumId">The Id of the album.</param>
/// <param name="trackId">The Id of the track.</param>
/// <returns>The created album entity, with its track.</returns>
private AlbumEntity CreateAlbumWithTrack(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
private void StubAlbum(Guid libraryId, Guid artistId, Guid albumId)
{
TrackEntity track = _trackEntityFixture.Create(
id: trackId,
albumId: albumId,
libraryId: libraryId,
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
return _albumEntityFixture.Create(
id: albumId,
artistId: artistId,
libraryId: libraryId,
tracks: [track],
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false);
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
}
/// <summary>
/// Stubs the artist and library repositories so that the handler finds the artist and the library.
/// Stubs the artist and library repositories so that the handler finds the artist and its library.
/// </summary>
/// <param name="artist">The artist returned by the artist repository.</param>
/// <param name="libraryId">The Id of the media library returned by the library repository.</param>
private void StubArtistAndLibrary(ArtistEntity artist, Guid libraryId)
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
private void StubArtistAndLibrary(Guid libraryId, Guid artistId)
{
_mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
StubArtist(libraryId, artistId);
LibraryEntity library = _libraryEntityFixture.Create(id: libraryId);
_mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
_mockLibraryRepository.GetByIdAsync(libraryId, Arg.Any<bool>(), shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
}
}
@@ -0,0 +1,389 @@
#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.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.Tracks.Commands.RestoreTrack;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
/// <summary>
/// Contains unit tests for the <see cref="RestoreTrackCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreTrackCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ITrackRepository _mockTrackRepository;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<RestoreTrackCommand> _mockValidator;
private readonly RestoreTrackCommandHandler _sut;
private readonly Guid _userId;
private readonly RestoreTrackCommandFixture _restoreTrackCommandFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreTrackCommandHandlerTests"/> class.
/// </summary>
public RestoreTrackCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockTrackRepository = Substitute.For<ITrackRepository>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<RestoreTrackCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the restoration, restoring the deleted
// track succeeds, and saving changes succeeds.
_mockValidator.Validate(Arg.Any<RestoreTrackCommand>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockTrackRepository.RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.Success);
_sut = new RestoreTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenDeletedTrackExists_ShouldRestoreTrackAndReturnUpdated()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false));
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false);
_mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
await _mockTrackRepository.Received(1).RestoreSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().SoftDeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
_mockValidator.Validate(Arg.Any<RestoreTrackCommand>())
.Returns([DomainErrors.Music.TrackIdCannotBeEmpty]);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.TrackIdCannotBeEmpty, result.FirstError);
await _mockTrackRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockTrackRepository.DidNotReceive().GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTrackRepositoryFails_ShouldReturnFailureResultWithoutRestoring()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
_mockTrackRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletedTrackDoesNotExist_ShouldReturnTrackNotFoundError()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
_mockTrackRepository.GetSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(_ => Result.From<TrackEntity?>(null));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTrackBelongsToAnotherLibrary_ShouldReturnTrackNotFoundWithoutEvaluatingThePolicy()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
(_, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: Guid.NewGuid(), includeMetadata: false));
_mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the track exists in another library.
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTrackBelongsToAnotherAlbum_ShouldReturnTrackNotFoundWithoutEvaluatingThePolicy()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
(Guid libraryId, _, Guid albumId, Guid trackId) = GetCommandIds(command);
TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: Guid.NewGuid(), libraryId: libraryId, includeMetadata: false));
_mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the track exists under another album.
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false));
_mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutRestoring()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
(Guid libraryId, _, Guid albumId, Guid trackId) = GetCommandIds(command);
TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false));
_mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnTrackNotFoundError()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
(Guid libraryId, _, Guid albumId, Guid trackId) = GetCommandIds(command);
TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false));
_mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(_ => Result.From<AlbumEntity?>(null));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
// The deleted track is only restorable while its album is visible, so a missing album is reported as a missing track.
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnTrackNotFoundError()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
(Guid libraryId, _, Guid albumId, Guid trackId) = GetCommandIds(command);
TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false));
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId, includeTracks: false);
_mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
await _mockTrackRepository.DidNotReceive().RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRestoreFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false));
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false);
_mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.RestoreSoftDeletedByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockTrackRepository.Received(1).RestoreSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command);
TrackEntity track = MarkAsDeleted(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false));
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false);
_mockTrackRepository.GetSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<Updated> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
await _mockTrackRepository.Received(1).RestoreSoftDeletedByIdAsync(trackId, Arg.Any<CancellationToken>());
}
/// <summary>
/// Extracts the parsed identifiers carried by <paramref name="command"/>.
/// </summary>
/// <param name="command">The command whose route identifiers are extracted.</param>
/// <returns>The parsed library, artist, album and track identifiers.</returns>
private static (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) GetCommandIds(RestoreTrackCommand command)
{
return (
Guid.Parse(command.LibraryId!),
Guid.Parse(command.ArtistId!),
Guid.Parse(command.AlbumId!),
Guid.Parse(command.TrackId!));
}
/// <summary>
/// Marks <paramref name="track"/> as soft deleted, the way the track repository returns it to the restore handler.
/// </summary>
/// <param name="track">The track to mark as soft deleted.</param>
/// <returns>The same <paramref name="track"/> instance, marked as soft deleted.</returns>
private static TrackEntity MarkAsDeleted(TrackEntity track)
{
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow;
return track;
}
}
@@ -0,0 +1,159 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
/// <summary>
/// Contains unit tests for the <see cref="RestoreTrackCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreTrackCommandValidatorTests
{
private readonly RestoreTrackCommandFixture _restoreTrackCommandFixture = new();
private readonly RestoreTrackCommandValidator _validator = new();
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-an-artist-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId)
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-an-album-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId)
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create(albumId: albumId, includeAlbumId: albumId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
}
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-track-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveValidationError(string? trackId)
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create(trackId: trackId, includeTrackId: trackId is not null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create(artistId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create(albumId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenTrackIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create(trackId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
RestoreTrackCommand command = _restoreTrackCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,196 @@
#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.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.Tracks.Queries.GetDeletedTracks;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Primitives;
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;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedTracksQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedTracksQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ITrackRepository _mockTrackRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetDeletedTracksQuery> _mockValidator;
private readonly GetDeletedTracksQueryHandler _sut;
private readonly Guid _userId;
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly GetDeletedTracksQueryFixture _getDeletedTracksQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedTracksQueryHandlerTests"/> class.
/// </summary>
public GetDeletedTracksQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockTrackRepository = Substitute.For<ITrackRepository>();
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetDeletedTracksQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the query is valid, the current user is authenticated, the library ownership policy allows access and there are no deleted tracks.
_mockValidator.Validate(Arg.Any<GetDeletedTracksQuery>()).Returns([]);
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockTrackRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([]));
_sut = new GetDeletedTracksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenDeletedTracksExist_ShouldReturnTheirMappedResponses()
{
// Arrange
GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
DateTime firstDeletedOnUtc = new(2026, 3, 10, 9, 15, 0, DateTimeKind.Utc);
AlbumEntity firstAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false);
ArtistEntity firstArtist = _artistEntityFixture.Create(id: firstAlbum.ArtistId, libraryId: libraryId, includeAlbums: false, includeContributors: false);
firstAlbum.Artist = firstArtist;
TrackEntity firstTrack = _trackEntityFixture.Create(albumId: firstAlbum.Id, libraryId: libraryId, includeMetadata: false);
firstTrack.IsDeleted = true;
firstTrack.DeletedOnUtc = firstDeletedOnUtc;
firstTrack.Album = firstAlbum;
AlbumEntity secondAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false);
ArtistEntity secondArtist = _artistEntityFixture.Create(id: secondAlbum.ArtistId, libraryId: libraryId, includeAlbums: false, includeContributors: false);
secondAlbum.Artist = secondArtist;
// A deleted track without a recorded deletion time falls back to its creation time, so the history never shows a default date.
TrackEntity secondTrack = _trackEntityFixture.Create(albumId: secondAlbum.Id, libraryId: libraryId, includeMetadata: false);
secondTrack.IsDeleted = true;
secondTrack.DeletedOnUtc = null;
secondTrack.Album = secondAlbum;
_mockTrackRepository.GetSoftDeletedByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([firstTrack, secondTrack]));
// Act
Result<IReadOnlyList<DeletedTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(firstTrack.Id, result.Value[0].Id);
Assert.Equal(firstTrack.LibraryId, result.Value[0].LibraryId);
Assert.Equal(firstArtist.Id, result.Value[0].ArtistId);
Assert.Equal(firstArtist.Name, result.Value[0].ArtistName);
Assert.Equal(firstAlbum.Id, result.Value[0].AlbumId);
Assert.Equal(firstAlbum.Title, result.Value[0].AlbumTitle);
Assert.Equal(firstTrack.Title, result.Value[0].Title);
Assert.Equal(firstTrack.Path, result.Value[0].Path);
Assert.Equal(firstDeletedOnUtc, result.Value[0].DeletedOnUtc);
Assert.Equal(secondTrack.Id, result.Value[1].Id);
Assert.Equal(secondTrack.CreatedOnUtc, result.Value[1].DeletedOnUtc);
}
[Fact]
public async Task HandleAsync_WhenThereAreNoDeletedTracks_ShouldReturnAnEmptyCollection()
{
// Arrange
GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create();
// Act
Result<IReadOnlyList<DeletedTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
{
// Arrange
GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetDeletedTracksQuery>())
.Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]);
// Act
Result<IReadOnlyList<DeletedTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError);
await _mockTrackRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<DeletedTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockTrackRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create();
Guid libraryId = Guid.Parse(query.LibraryId!);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<IReadOnlyList<DeletedTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTrackRepositoryFails_ShouldReturnFailureResult()
{
// Arrange
GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create();
_mockTrackRepository.GetSoftDeletedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<IReadOnlyList<DeletedTrackResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedTracksQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedTracksQueryValidatorTests
{
private readonly GetDeletedTracksQueryFixture _getDeletedTracksQueryFixture = new();
private readonly GetDeletedTracksQueryValidator _validator = new();
[Theory]
[InlineData(null)] // missing route value
[InlineData("")] // empty route value
[InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
[InlineData("not-a-library-guid")] // non-Guid route value
[InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
{
// Arrange
GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create(libraryId: Guid.NewGuid().ToString());
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors()
{
// Arrange
GetDeletedTracksQuery query = _getDeletedTracksQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -2,12 +2,15 @@
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.Core.MediaLibrary.Management.Deletion;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.Common.Errors;
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 Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
@@ -29,10 +32,13 @@ public class MusicMediaLibraryItemDeletionStrategyTests
private readonly IAlbumRepository _mockAlbumRepository;
private readonly IArtistRepository _mockArtistRepository;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly IMusicArtworkService _mockMusicArtworkService;
private readonly ILogger<MusicMediaLibraryItemDeletionStrategy> _mockLogger;
private readonly MusicMediaLibraryItemDeletionStrategy _sut;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MusicMediaLibraryItemDeletionStrategyTests"/> class.
@@ -44,12 +50,18 @@ public class MusicMediaLibraryItemDeletionStrategyTests
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
_mockLogger = Substitute.For<ILogger<MusicMediaLibraryItemDeletionStrategy>>();
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
_mockMusicArtworkService.DeleteStoredArtwork(Arg.Any<string>())
.Returns(Result.Deleted);
_sut = new MusicMediaLibraryItemDeletionStrategy(_mockUnitOfWork);
_sut = new MusicMediaLibraryItemDeletionStrategy(_mockUnitOfWork, _mockMusicArtworkService, _mockLogger);
}
[Fact]
@@ -67,9 +79,9 @@ public class MusicMediaLibraryItemDeletionStrategyTests
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
_mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([otherTrack]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
@@ -80,6 +92,11 @@ public class MusicMediaLibraryItemDeletionStrategyTests
Assert.True(result.IsSuccess);
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>());
await _mockTrackRepository.Received(1).DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>());
// The album and its remaining tracks are read including the soft deleted ones, so a hidden track still keeps the album alive.
await _mockAlbumRepository.Received(1).GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockTrackRepository.Received(1).GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockTrackRepository.DidNotReceive().GetByAlbumIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Album, Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
@@ -102,15 +119,15 @@ public class MusicMediaLibraryItemDeletionStrategyTests
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
_mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
_mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([otherAlbum]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
@@ -121,6 +138,9 @@ public class MusicMediaLibraryItemDeletionStrategyTests
Assert.True(result.IsSuccess);
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>());
await _mockAlbumRepository.Received(1).DeleteByIdAsync(albumId, Arg.Any<CancellationToken>());
// The remaining albums of the artist are read including the soft deleted ones, so a hidden album still keeps the artist alive.
await _mockAlbumRepository.Received(1).GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -141,15 +161,15 @@ public class MusicMediaLibraryItemDeletionStrategyTests
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
_mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
_mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
@@ -166,9 +186,113 @@ public class MusicMediaLibraryItemDeletionStrategyTests
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>());
await _mockAlbumRepository.Received(1).DeleteByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any<CancellationToken>());
// Every scoping read includes the soft deleted rows, so hidden siblings are never missed when deciding what to remove.
await _mockAlbumRepository.Received(1).GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockTrackRepository.Received(1).GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>());
await _mockAlbumRepository.Received(1).GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenEveryItemHasStoredArtwork_ShouldDeleteEveryStoredFileAndRow()
{
// 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);
MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id, fileName: "/media/music/track-cover.jpg");
MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, fileName: "/media/music/album-cover.jpg");
MusicArtworkEntity artistArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, fileName: "/media/music/artist-cover.jpg");
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([trackArtwork]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([albumArtwork]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([artistArtwork]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockArtistRepository.DeleteByIdAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(trackArtwork.FileName!);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(albumArtwork.FileName!);
_mockMusicArtworkService.Received(1).DeleteStoredArtwork(artistArtwork.FileName!);
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task DeleteItemAsync_WhenDeletingAStoredArtworkFileFails_ShouldLogAWarningAndStillDeleteTheRow()
{
// 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);
MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id, fileName: "/media/music/track-cover.jpg");
_mockTrackRepository.GetByPathAsync(libraryId.Value, track.Path, Arg.Any<CancellationToken>())
.Returns(Result.From<TrackEntity?>(track));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([trackArtwork]));
_mockMusicArtworkService.DeleteStoredArtwork(trackArtwork.FileName!)
.Returns(Errors.FileSystemManagement.FileNotFound);
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([otherAlbum]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
Result<Success> result = await _sut.DeleteItemAsync(libraryId.Value, track.Path, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Track, track.Id, Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to delete the stored")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task DeleteItemAsync_WhenAlbumWasAlreadyRemoved_ShouldPersistTheTrackDeletion()
{
@@ -182,7 +306,7 @@ public class MusicMediaLibraryItemDeletionStrategyTests
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(null));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
@@ -192,6 +316,8 @@ public class MusicMediaLibraryItemDeletionStrategyTests
// Assert
Assert.True(result.IsSuccess);
await _mockTrackRepository.Received(1).DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>());
// A soft deleted album is still read, because its own tracks have to keep it alive until their files disappear too.
await _mockAlbumRepository.Received(1).GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -271,9 +397,9 @@ public class MusicMediaLibraryItemDeletionStrategyTests
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
_mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(error);
@@ -304,15 +430,15 @@ public class MusicMediaLibraryItemDeletionStrategyTests
.Returns(Result.Deleted);
_mockTrackRepository.DeleteByIdAsync(track.Id, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByIdAsync(albumId, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
_mockAlbumRepository.GetIncludingDeletedByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any<CancellationToken>())
_mockTrackRepository.GetByAlbumIdIncludingDeletedAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<TrackEntity>>([track]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockAlbumRepository.DeleteByIdAsync(albumId, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Deleted));
_mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any<CancellationToken>())
_mockAlbumRepository.GetByArtistIdIncludingDeletedAsync(artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
_mockMusicArtworkRepository.DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(error);
@@ -79,8 +79,8 @@ public class LibraryDeletedDomainEventHandlerTests
// 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));
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => PathSegment.Create($"{callInfo.ArgAt<string>(0)}-{callInfo.ArgAt<string>(1)}", isDirectory: false, isDrive: false));
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockDirectoryProviderService.DeleteDirectory(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
@@ -234,14 +234,14 @@ public class LibraryDeletedDomainEventHandlerTests
}
[Fact]
public async Task HandleAsync_WhenSanitizeSegmentFails_ShouldThrowEventualConsistencyExceptionWithoutDeletingItemDirectories()
public async Task HandleAsync_WhenSanitizeCompositeSegmentFails_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);
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>()).Returns(error);
// Act
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
@@ -274,7 +274,7 @@ public class LibraryDeletedDomainEventHandlerTests
await _sut.HandleAsync(domainEvent, CancellationToken.None);
// Assert
_mockPathService.Received(1).SanitizeSegment(librarySegment);
_mockPathService.Received(1).SanitizeCompositeSegment(libraryTitle, libraryId.ToString());
_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));
@@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
@@ -36,6 +37,7 @@ public class AlbumRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly ITrackRepository _mockTrackRepository;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly AlbumRepository _sut;
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
@@ -61,7 +63,9 @@ public class AlbumRepositoryTests
_mockTrackRepository.UpdateAsync(Arg.Any<TrackEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockTrackRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_sut = new AlbumRepository(_mockContext, _mockTrackRepository);
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc));
_sut = new AlbumRepository(_mockContext, _mockTrackRepository, _mockDateTimeProvider);
}
[Fact]
@@ -270,6 +274,7 @@ public class AlbumRepositoryTests
{
// Arrange
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(storedAlbum);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
@@ -297,6 +302,7 @@ public class AlbumRepositoryTests
Guid storedArtistId = Guid.NewGuid();
Guid storedLibraryId = Guid.NewGuid();
AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtistId, libraryId: storedLibraryId, includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(storedArtistId, storedLibraryId);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
@@ -328,6 +334,7 @@ public class AlbumRepositoryTests
storedAlbum.CreatedBy = storedCreatedBy;
storedAlbum.UpdatedOnUtc = null;
storedAlbum.UpdatedBy = null;
await SeedVisibleArtistAsync(storedAlbum);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
@@ -365,6 +372,7 @@ public class AlbumRepositoryTests
_audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10),
_audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20)
];
await SeedVisibleArtistAsync(storedAlbum);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
@@ -402,6 +410,7 @@ public class AlbumRepositoryTests
AlbumContributorEntity keptContributor = _albumContributorEntityFixture.Create(
albumId: storedAlbum.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer);
storedAlbum.Contributors = [keptContributor];
await SeedVisibleArtistAsync(storedAlbum);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
@@ -437,6 +446,7 @@ public class AlbumRepositoryTests
AlbumContributorEntity removedContributor = _albumContributorEntityFixture.Create(
albumId: storedAlbum.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Composer);
storedAlbum.Contributors = [keptContributor, removedContributor];
await SeedVisibleArtistAsync(storedAlbum);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
@@ -474,6 +484,7 @@ public class AlbumRepositoryTests
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
storedAlbum.Tags = [existingTag];
storedAlbum.Genres = [existingGenre];
await SeedVisibleArtistAsync(storedAlbum);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
@@ -506,6 +517,7 @@ public class AlbumRepositoryTests
{
// Arrange
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false, catalogNumbers: ["EMC 3006", "OC 062 o 94519"]);
await SeedVisibleArtistAsync(storedAlbum);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
@@ -532,6 +544,7 @@ public class AlbumRepositoryTests
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
@@ -595,6 +608,8 @@ public class AlbumRepositoryTests
AlbumEntity secondAlphaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Alpha", includeTracks: false, includeMetadata: false);
AlbumEntity firstAlphaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Alpha", includeTracks: false, includeMetadata: false);
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(title: "Gamma", includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(artistId, betaAlbum.LibraryId);
await SeedVisibleArtistAsync(albumOfAnotherArtist);
_mockContext.Albums.AddRange(betaAlbum, secondAlphaAlbum, firstAlphaAlbum, albumOfAnotherArtist);
await _mockContext.SaveChangesAsync();
@@ -646,6 +661,8 @@ public class AlbumRepositoryTests
AlbumEntity secondAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Album B", includeTracks: false, includeMetadata: false);
AlbumEntity firstAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Album A", includeTracks: false, includeMetadata: false);
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(title: "Album C", includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(artistId, secondAlbum.LibraryId);
await SeedVisibleArtistAsync(albumOfAnotherArtist);
_mockContext.Albums.AddRange(secondAlbum, firstAlbum, albumOfAnotherArtist);
await _mockContext.SaveChangesAsync();
@@ -679,6 +696,7 @@ public class AlbumRepositoryTests
albums[index].Title = $"Album {index}";
albums[index].Tracks = [];
}
await SeedVisibleArtistAsync(artistId, albums[0].LibraryId);
_mockContext.Albums.AddRange(albums);
await _mockContext.SaveChangesAsync();
@@ -704,6 +722,8 @@ public class AlbumRepositoryTests
Guid artistId = Guid.NewGuid();
AlbumEntity albumOfArtist = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false);
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(artistId, albumOfArtist.LibraryId);
await SeedVisibleArtistAsync(albumOfAnotherArtist);
_mockContext.Albums.AddRange(albumOfArtist, albumOfAnotherArtist);
await _mockContext.SaveChangesAsync();
@@ -726,6 +746,7 @@ public class AlbumRepositoryTests
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false);
album.TotalTracks = 12;
await SeedVisibleArtistAsync(album);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
@@ -749,6 +770,7 @@ public class AlbumRepositoryTests
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId, originalReleaseYear: 1975, reReleaseYear: 2011, includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
@@ -770,6 +792,7 @@ public class AlbumRepositoryTests
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId, originalReleaseYear: 1975, includeReReleaseYear: false, includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
@@ -791,6 +814,7 @@ public class AlbumRepositoryTests
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId, releaseType: MusicReleaseType.Single, includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
@@ -812,6 +836,7 @@ public class AlbumRepositoryTests
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
_mockContext.Albums.Add(album);
_mockContext.MusicArtwork.Add(
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id, artworkType: ArtworkType.Cover, fileName: "covers/opera.jpg"));
@@ -834,6 +859,7 @@ public class AlbumRepositoryTests
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
@@ -857,6 +883,10 @@ public class AlbumRepositoryTests
AlbumEntity failedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Failed);
AlbumEntity enrichedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Enriched);
AlbumEntity albumOfAnotherLibrary = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
await SeedVisibleArtistAsync(pendingAlbum);
await SeedVisibleArtistAsync(failedAlbum);
await SeedVisibleArtistAsync(enrichedAlbum);
await SeedVisibleArtistAsync(albumOfAnotherLibrary);
_mockContext.Albums.AddRange(pendingAlbum, failedAlbum, enrichedAlbum, albumOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
@@ -868,6 +898,550 @@ public class AlbumRepositoryTests
Assert.Equal(2, result.Value);
}
[Fact]
public async Task GetByIdAsync_WhenAlbumIsSoftDeleted_ShouldReturnNull()
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await _sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByIdAsync_WhenItsArtistIsSoftDeleted_ShouldReturnNull()
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
ArtistEntity artist = await SeedVisibleArtistAsync(album);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await _sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None);
// Assert
// A deleted artist hides every album it owns, because the albums are only reachable through it.
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByArtistIdAsync_WhenAnAlbumIsSoftDeleted_ShouldExcludeIt()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity activeAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Active", includeTracks: false, includeMetadata: false);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Deleted", includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(artistId, activeAlbum.LibraryId);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.AddRange(activeAlbum, deletedAlbum);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<AlbumEntity>> result = await _sut.GetByArtistIdAsync(artistId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeAlbum.Id, Assert.Single(result.Value).Id);
}
[Fact]
public async Task GetByArtistIdAsync_WhenTheArtistIsSoftDeleted_ShouldReturnEmpty()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false);
ArtistEntity artist = await SeedVisibleArtistAsync(artistId, album.LibraryId);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<AlbumEntity>> result = await _sut.GetByArtistIdAsync(artistId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetByArtistIdIncludingDeletedAsync_WhenCalled_ShouldReturnEveryAlbumOfTheArtistOrderedByTitleThenId()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity betaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Beta", includeTracks: false, includeMetadata: false);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Alpha", includeTracks: false, includeMetadata: false);
AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(title: "Gamma", includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(artistId, betaAlbum.LibraryId);
await SeedVisibleArtistAsync(albumOfAnotherArtist);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.AddRange(betaAlbum, deletedAlbum, albumOfAnotherArtist);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<AlbumEntity>> result = await _sut.GetByArtistIdIncludingDeletedAsync(artistId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([deletedAlbum.Id, betaAlbum.Id], result.Value.Select(album => album.Id));
}
[Fact]
public async Task GetIncludingDeletedByIdAsync_WhenAlbumIsSoftDeleted_ShouldReturnIt()
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await _sut.GetIncludingDeletedByIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(album.Id, result.Value!.Id);
Assert.True(result.Value.IsDeleted);
}
[Fact]
public async Task GetIncludingDeletedByIdAsync_WhenAlbumDoesNotExist_ShouldReturnNull()
{
// Act
Result<AlbumEntity?> result = await _sut.GetIncludingDeletedByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetAlbumsLiteByArtistIdAsync_WhenAnAlbumIsSoftDeleted_ShouldExcludeIt()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity activeAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Active", includeTracks: false, includeMetadata: false);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Deleted", includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(artistId, activeAlbum.LibraryId);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.AddRange(activeAlbum, deletedAlbum);
await _mockContext.SaveChangesAsync();
// Act
Result<PaginatedResultDto<AlbumLiteRow>> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeAlbum.Id, Assert.Single(result.Value.Data).Id);
}
[Fact]
public async Task GetByTitleAsync_WhenAlbumIsSoftDeleted_ShouldReturnNull()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(artistId, album.LibraryId);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await _sut.GetByTitleAsync(artistId, "A Night at the Opera", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByTitleAsync_WhenItsArtistIsSoftDeleted_ShouldReturnNull()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false);
ArtistEntity artist = await SeedVisibleArtistAsync(artistId, album.LibraryId);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await _sut.GetByTitleAsync(artistId, "A Night at the Opera", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByTrackDirectoryAsync_WhenAlbumIsSoftDeleted_ShouldReturnNull()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/a-night-at-the-opera/bohemian-rhapsody.flac", includeMetadata: false);
album.Tracks = [track];
await SeedVisibleArtistAsync(artistId, album.LibraryId);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await _sut.GetByTrackDirectoryAsync(artistId, "/music/queen/a-night-at-the-opera", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenAlbumIsDeleted_ShouldReturnIt()
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await _sut.GetSoftDeletedByIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(album.Id, result.Value!.Id);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenItsArtistIsDeleted_ShouldReturnNull()
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
ArtistEntity artist = await SeedVisibleArtistAsync(album);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddHours(-2);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await _sut.GetSoftDeletedByIdAsync(album.Id, CancellationToken.None);
// Assert
// A deleted artist hides its own deleted albums from the deleted items page, so the album is not offered for a restore that would stay hidden.
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenAlbumIsNotDeleted_ShouldReturnNull()
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<AlbumEntity?> result = await _sut.GetSoftDeletedByIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyTheDeletedAlbumsOfVisibleArtists()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AlbumEntity deletedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
ArtistEntity visibleArtist = await SeedVisibleArtistAsync(deletedAlbum);
AlbumEntity deletedAlbumOfDeletedArtist = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
ArtistEntity deletedArtist = await SeedVisibleArtistAsync(deletedAlbumOfDeletedArtist);
AlbumEntity activeAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(activeAlbum);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
deletedAlbumOfDeletedArtist.IsDeleted = true;
deletedAlbumOfDeletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-2);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-3);
_mockContext.Albums.AddRange(deletedAlbum, deletedAlbumOfDeletedArtist, activeAlbum);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<AlbumEntity>> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(deletedAlbum.Id, Assert.Single(result.Value).Id);
}
[Fact]
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldOrderByTheStoredDeletionTimeThenTitleAndId()
{
// Arrange
Guid libraryId = Guid.NewGuid();
DateTime deletedOnUtc = new(2026, 11, 14, 10, 0, 0, DateTimeKind.Utc);
AlbumEntity olderDeletion = _albumEntityFixture.Create(libraryId: libraryId, title: "Beta", includeTracks: false, includeMetadata: false);
AlbumEntity newerDeletion = _albumEntityFixture.Create(libraryId: libraryId, title: "Alpha", includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(olderDeletion);
await SeedVisibleArtistAsync(newerDeletion);
olderDeletion.IsDeleted = true;
olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2);
olderDeletion.UpdatedOnUtc = deletedOnUtc;
newerDeletion.IsDeleted = true;
newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1);
newerDeletion.UpdatedOnUtc = deletedOnUtc.AddDays(-5);
_mockContext.Albums.AddRange(olderDeletion, newerDeletion);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<AlbumEntity>> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([newerDeletion.Id, olderDeletion.Id], result.Value.Select(album => album.Id));
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldClearTheDeletionStateAndTime()
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.False(album.IsDeleted);
Assert.Null(album.DeletedOnUtc);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenAlbumIsNotDeleted_ShouldReturnAlbumNotFound()
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFound()
{
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenAlbumIsSoftDeleted_ShouldReturnAlbumNotFound()
{
// Arrange
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(storedAlbum);
storedAlbum.IsDeleted = true;
storedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false);
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenItsArtistIsSoftDeleted_ShouldReturnAlbumNotFound()
{
// Arrange
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
ArtistEntity artist = await SeedVisibleArtistAsync(storedAlbum);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false);
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenIncomingDeletionStateDiffers_ShouldPreserveTheActiveStateAndClearItsModifiedFlags()
{
// Arrange
AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(storedAlbum);
_mockContext.Albums.Add(storedAlbum);
await _mockContext.SaveChangesAsync();
AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false);
data.Title = "A Night at the Opera";
data.IsDeleted = true;
data.DeletedOnUtc = DateTime.UtcNow;
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
EntityEntry<AlbumEntity> entry = _mockContext.Entry(storedAlbum);
Assert.False(storedAlbum.IsDeleted);
Assert.Null(storedAlbum.DeletedOnUtc);
Assert.False(entry.Property(album => album.IsDeleted).IsModified);
Assert.False(entry.Property(album => album.DeletedOnUtc).IsModified);
}
[Fact]
public async Task GetAlbumsNeedingMetadataCountAsync_WhenAnAlbumIsSoftDeleted_ShouldNotCountIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AlbumEntity pendingAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
await SeedVisibleArtistAsync(pendingAlbum);
await SeedVisibleArtistAsync(deletedAlbum);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.AddRange(pendingAlbum, deletedAlbum);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetAlbumsNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value);
}
[Fact]
public async Task GetFirstTrackPathsByAlbumIdsAsync_WhenTheOnlyTrackIsSoftDeleted_ShouldNotReturnItsPath()
{
// Arrange
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(album);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, path: "/music/queen/deleted.flac", includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
album.Tracks = [deletedTrack];
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyDictionary<Guid, string>> result = await _sut.GetFirstTrackPathsByAlbumIdsAsync([albumId], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetAlbumsNeedingArtworkCountAsync_WhenAnAlbumIsSoftDeleted_ShouldNotCountIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AlbumEntity activeAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
await SeedVisibleArtistAsync(activeAlbum);
await SeedVisibleArtistAsync(deletedAlbum);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Albums.AddRange(activeAlbum, deletedAlbum);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetAlbumsNeedingArtworkCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value);
}
/// <summary>
/// Seeds an artist with the identity of the provided album, so that the album is part of a visible catalogue and its ancestor filters pass.
/// </summary>
/// <param name="album">The album whose artist is seeded.</param>
/// <returns>The persisted artist.</returns>
private Task<ArtistEntity> SeedVisibleArtistAsync(AlbumEntity album)
{
return SeedVisibleArtistAsync(album.ArtistId, album.LibraryId);
}
/// <summary>
/// Seeds the artist identified by <paramref name="artistId"/>, unless it is already stored, so that the albums owned by it are part of a visible catalogue.
/// </summary>
/// <param name="artistId">The Id of the artist to seed.</param>
/// <param name="libraryId">The Id of the library that owns the artist.</param>
/// <returns>The persisted artist.</returns>
private async Task<ArtistEntity> SeedVisibleArtistAsync(Guid artistId, Guid libraryId)
{
ArtistEntity? artist = await _mockContext.Artists.FirstOrDefaultAsync(candidate => candidate.Id == artistId);
if (artist is null)
{
artist = _artistEntityFixture.Create(
id: artistId,
libraryId: libraryId,
includeAlbums: false,
includeContributors: false);
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
}
return artist;
}
/// <summary>
/// Creates an album that belongs to the artist identified by <paramref name="artistId"/>, with every related collection populated deterministically.
/// </summary>
@@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DTO.Filtering;
@@ -19,6 +20,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -36,6 +38,7 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary;
public class ArtistRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly AlbumRepository _albumRepository;
private readonly TrackRepository _trackRepository;
private readonly ArtistRepository _sut;
@@ -61,9 +64,11 @@ public class ArtistRepositoryTests
public ArtistRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_trackRepository = new TrackRepository(_mockContext);
_albumRepository = new AlbumRepository(_mockContext, _trackRepository);
_sut = new ArtistRepository(_mockContext, _albumRepository, _trackRepository);
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc));
_trackRepository = new TrackRepository(_mockContext, _mockDateTimeProvider);
_albumRepository = new AlbumRepository(_mockContext, _trackRepository, _mockDateTimeProvider);
_sut = new ArtistRepository(_mockContext, _albumRepository, _trackRepository, _mockDateTimeProvider);
}
[Fact]
@@ -1311,6 +1316,554 @@ public class ArtistRepositoryTests
Assert.Equal(["Beneath the Surface", "The Beatles"], result.Value.Data.Select(row => row.Name));
}
[Fact]
public async Task GetByIdAsync_WhenArtistIsSoftDeleted_ShouldReturnNull()
{
// Arrange
ArtistEntity deletedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Artists.Add(deletedArtist);
await _mockContext.SaveChangesAsync();
// Act
Result<ArtistEntity?> result = await _sut.GetByIdAsync(deletedArtist.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetAllAsync_WhenArtistsAreSoftDeleted_ShouldExcludeThem()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity activeArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Artists.AddRange(activeArtist, deletedArtist);
await _mockContext.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<ArtistEntity>> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeArtist.Id, Assert.Single(result.Value.Data).Id);
}
[Fact]
public async Task GetAllLiteAsync_WhenArtistsAreSoftDeleted_ShouldExcludeThem()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity activeArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Artists.AddRange(activeArtist, deletedArtist);
await _mockContext.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeArtist.Id, Assert.Single(result.Value.Data).Id);
}
[Fact]
public async Task GetByNameAsync_WhenArtistIsActive_ShouldReturnIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<ArtistEntity?> result = await _sut.GetByNameAsync(libraryId, "Queen", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(artist.Id, result.Value!.Id);
}
[Fact]
public async Task GetByNameAsync_WhenOnlyASoftDeletedArtistHasTheName_ShouldReturnNull()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Artists.Add(deletedArtist);
await _mockContext.SaveChangesAsync();
// Act
Result<ArtistEntity?> result = await _sut.GetByNameAsync(libraryId, "Queen", CancellationToken.None);
// Assert
// A deleted artist keeps its name only for a restore, so a scan that finds the name again must materialize a new visible artist.
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task InsertAsync_WhenOnlyASoftDeletedArtistHasTheSameName_ShouldAddArtistAndReturnCreated()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Artists.Add(deletedArtist);
await _mockContext.SaveChangesAsync();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
// Act
Result<Created> result = await _sut.InsertAsync(artist, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
Assert.Contains(_mockContext.ChangeTracker.Entries<ArtistEntity>(), entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenArtistIsDeleted_ShouldReturnIt()
{
// Arrange
ArtistEntity deletedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Artists.Add(deletedArtist);
await _mockContext.SaveChangesAsync();
// Act
Result<ArtistEntity?> result = await _sut.GetSoftDeletedByIdAsync(deletedArtist.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(deletedArtist.Id, result.Value!.Id);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenArtistIsNotDeleted_ShouldReturnNull()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<ArtistEntity?> result = await _sut.GetSoftDeletedByIdAsync(artist.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenArtistDoesNotExist_ShouldReturnNull()
{
// Act
Result<ArtistEntity?> result = await _sut.GetSoftDeletedByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyTheDeletedArtistsOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity activeArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
ArtistEntity otherLibraryDeletedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
otherLibraryDeletedArtist.IsDeleted = true;
otherLibraryDeletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-2);
_mockContext.Artists.AddRange(activeArtist, deletedArtist, otherLibraryDeletedArtist);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<ArtistEntity>> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(deletedArtist.Id, Assert.Single(result.Value).Id);
}
[Fact]
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldOrderByTheStoredDeletionTimeThenNameAndId()
{
// Arrange
Guid libraryId = Guid.NewGuid();
DateTime deletedOnUtc = new(2026, 11, 14, 10, 0, 0, DateTimeKind.Utc);
ArtistEntity olderDeletion = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false);
olderDeletion.IsDeleted = true;
olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2);
olderDeletion.UpdatedOnUtc = DateTime.UtcNow;
ArtistEntity newerDeletion = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false);
newerDeletion.IsDeleted = true;
newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1);
newerDeletion.UpdatedOnUtc = deletedOnUtc.AddDays(-5);
_mockContext.Artists.AddRange(olderDeletion, newerDeletion);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<ArtistEntity>> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
// A later write to a hidden row may change its update time, but it must not change the order of the deleted items.
Assert.False(result.IsFailure);
Assert.Equal([newerDeletion.Id, olderDeletion.Id], result.Value.Select(artist => artist.Id));
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenCalled_ShouldSetTheDeletionStateAndTimeFromTheProvider()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.SoftDeleteByIdAsync(artist.Id, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.True(artist.IsDeleted);
Assert.Equal(_mockDateTimeProvider.UtcNow, artist.DeletedOnUtc);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenArtistIsAlreadyDeleted_ShouldReturnArtistNotFound()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
DateTime storedDeletedOnUtc = DateTime.UtcNow.AddHours(-1);
artist.IsDeleted = true;
artist.DeletedOnUtc = storedDeletedOnUtc;
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.SoftDeleteByIdAsync(artist.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
Assert.Equal(storedDeletedOnUtc, artist.DeletedOnUtc);
}
[Fact]
public async Task SoftDeleteByIdAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFound()
{
// Act
Result<Updated> result = await _sut.SoftDeleteByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldClearTheDeletionStateAndTime()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(artist.Id, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.False(artist.IsDeleted);
Assert.Null(artist.DeletedOnUtc);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenArtistIsNotDeleted_ShouldReturnArtistNotFound()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(artist.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFound()
{
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenArtistIsSoftDeleted_ShouldReturnArtistNotFound()
{
// Arrange
ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
storedArtist.IsDeleted = true;
storedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Artists.Add(storedArtist);
await _mockContext.SaveChangesAsync();
ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false);
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenIncomingDeletionStateDiffers_ShouldPreserveTheActiveStateAndClearItsModifiedFlags()
{
// Arrange
ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
_mockContext.Artists.Add(storedArtist);
await _mockContext.SaveChangesAsync();
ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false);
data.Name = "Freddie Mercury";
data.IsDeleted = true;
data.DeletedOnUtc = DateTime.UtcNow;
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
EntityEntry<ArtistEntity> entry = _mockContext.Entry(storedArtist);
// The deletion state is owned by the explicit delete and restore operations, so an edit never writes it back.
Assert.False(storedArtist.IsDeleted);
Assert.Null(storedArtist.DeletedOnUtc);
Assert.False(entry.Property(artist => artist.IsDeleted).IsModified);
Assert.False(entry.Property(artist => artist.DeletedOnUtc).IsModified);
}
[Fact]
public async Task UpdateAsync_WhenAnAlbumIsSoftDeleted_ShouldKeepItInsteadOfRemovingIt()
{
// Arrange
ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
storedArtist.Albums = [deletedAlbum];
_mockContext.Artists.Add(storedArtist);
await _mockContext.SaveChangesAsync();
ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false);
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
AlbumEntity? retrievedAlbum = await _mockContext.Albums.FirstOrDefaultAsync(album => album.Id == deletedAlbum.Id);
Assert.NotNull(retrievedAlbum);
Assert.True(retrievedAlbum!.IsDeleted);
Assert.NotNull(retrievedAlbum.DeletedOnUtc);
}
[Fact]
public async Task UpdateAsync_WhenIncomingAlbumMatchesASoftDeletedAlbum_ShouldReturnAlbumNotFoundWithoutEditingIt()
{
// Arrange
ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, title: "Hidden Album", includeTracks: false, includeMetadata: false);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
storedArtist.Albums = [deletedAlbum];
_mockContext.Artists.Add(storedArtist);
await _mockContext.SaveChangesAsync();
AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: deletedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, title: "Edited Hidden Album", includeTracks: false, includeMetadata: false);
ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false);
data.Albums = [incomingAlbum];
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
AlbumEntity? retrievedAlbum = await _mockContext.Albums.FirstOrDefaultAsync(album => album.Id == deletedAlbum.Id);
Assert.NotNull(retrievedAlbum);
Assert.Equal("Hidden Album", retrievedAlbum!.Title);
Assert.True(retrievedAlbum.IsDeleted);
}
[Fact]
public async Task UpdateAsync_WhenATrackIsSoftDeleted_ShouldKeepItInsteadOfRemovingIt()
{
// Arrange
ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
storedAlbum.Tracks = [deletedTrack];
storedArtist.Albums = [storedAlbum];
_mockContext.Artists.Add(storedArtist);
await _mockContext.SaveChangesAsync();
AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: storedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false);
ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false);
data.Albums = [incomingAlbum];
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
TrackEntity? retrievedTrack = await _mockContext.Tracks.FirstOrDefaultAsync(track => track.Id == deletedTrack.Id);
Assert.NotNull(retrievedTrack);
Assert.True(retrievedTrack!.IsDeleted);
}
[Fact]
public async Task UpdateAsync_WhenIncomingTrackMatchesASoftDeletedTrack_ShouldReturnTrackNotFoundWithoutEditingIt()
{
// Arrange
ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, title: "Hidden Track", path: "/music/hidden.flac", includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
storedAlbum.Tracks = [deletedTrack];
storedArtist.Albums = [storedAlbum];
_mockContext.Artists.Add(storedArtist);
await _mockContext.SaveChangesAsync();
AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: storedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false);
TrackEntity incomingTrack = _trackEntityFixture.Create(id: deletedTrack.Id, albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, title: "Edited Hidden Track", path: "/music/moved.flac", includeMetadata: false);
incomingAlbum.Tracks = [incomingTrack];
ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false);
data.Albums = [incomingAlbum];
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
TrackEntity? retrievedTrack = await _mockContext.Tracks.FirstOrDefaultAsync(track => track.Id == deletedTrack.Id);
Assert.NotNull(retrievedTrack);
Assert.Equal("Hidden Track", retrievedTrack!.Title);
Assert.Equal("/music/hidden.flac", retrievedTrack.Path);
Assert.True(retrievedTrack.IsDeleted);
}
[Fact]
public async Task UpdateAsync_WhenIncomingTrackMatchesASoftDeletedTrackOfAnotherAlbum_ShouldReturnTrackNotFoundWithoutEditingIt()
{
// Arrange
ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, title: "Hidden Track", path: "/music/hidden.flac", includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
storedAlbum.Tracks = [deletedTrack];
storedArtist.Albums = [storedAlbum];
_mockContext.Artists.Add(storedArtist);
await _mockContext.SaveChangesAsync();
AlbumEntity newAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false);
TrackEntity incomingTrack = _trackEntityFixture.Create(id: deletedTrack.Id, albumId: newAlbum.Id, libraryId: storedArtist.LibraryId, title: "Moved Hidden Track", path: "/music/moved.flac", includeMetadata: false);
newAlbum.Tracks = [incomingTrack];
ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false);
data.Albums = [newAlbum];
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
TrackEntity? retrievedTrack = await _mockContext.Tracks.FirstOrDefaultAsync(track => track.Id == deletedTrack.Id);
Assert.NotNull(retrievedTrack);
Assert.Equal("Hidden Track", retrievedTrack!.Title);
Assert.Equal("/music/hidden.flac", retrievedTrack.Path);
Assert.Equal(storedAlbum.Id, retrievedTrack.AlbumId);
}
[Fact]
public async Task GetArtistsNeedingMetadataCountAsync_WhenAnArtistIsSoftDeleted_ShouldNotCountIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity pendingArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
pendingArtist.MetadataStatus = MetadataStatus.Pending;
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
deletedArtist.MetadataStatus = MetadataStatus.Pending;
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Artists.AddRange(pendingArtist, deletedArtist);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetArtistsNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value);
}
[Fact]
public async Task GetArtistsNeedingArtworkCountAsync_WhenAnArtistIsSoftDeleted_ShouldNotCountIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity activeArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Artists.AddRange(activeArtist, deletedArtist);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetArtistsNeedingArtworkCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value);
}
/// <summary>
/// Marks the provided artist, its albums and its tracks as enriched.
/// </summary>
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
@@ -16,6 +17,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -33,6 +35,7 @@ namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary;
public class TrackRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly TrackRepository _sut;
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new();
@@ -51,7 +54,9 @@ public class TrackRepositoryTests
public TrackRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new TrackRepository(_mockContext);
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockDateTimeProvider.UtcNow.Returns(new DateTime(2026, 11, 14, 10, 30, 0, DateTimeKind.Utc));
_sut = new TrackRepository(_mockContext, _mockDateTimeProvider);
}
[Fact]
@@ -279,6 +284,7 @@ public class TrackRepositoryTests
{
// Arrange
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
await SeedVisibleAncestorsAsync(storedTrack);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
@@ -320,6 +326,7 @@ public class TrackRepositoryTests
Guid storedAlbumId = Guid.NewGuid();
Guid storedLibraryId = Guid.NewGuid();
TrackEntity storedTrack = _trackEntityFixture.Create(albumId: storedAlbumId, libraryId: storedLibraryId, includeMetadata: false);
await SeedVisibleAncestorsAsync(storedTrack);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
@@ -350,6 +357,7 @@ public class TrackRepositoryTests
storedTrack.CreatedBy = storedCreatedBy;
storedTrack.UpdatedOnUtc = null;
storedTrack.UpdatedBy = null;
await SeedVisibleAncestorsAsync(storedTrack);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
@@ -385,6 +393,7 @@ public class TrackRepositoryTests
TrackContributorEntity keptContributor = _trackContributorEntityFixture.Create(
trackId: storedTrack.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer);
storedTrack.Contributors = [keptContributor];
await SeedVisibleAncestorsAsync(storedTrack);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
@@ -420,6 +429,7 @@ public class TrackRepositoryTests
TrackContributorEntity removedContributor = _trackContributorEntityFixture.Create(
trackId: storedTrack.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Producer);
storedTrack.Contributors = [keptContributor, removedContributor];
await SeedVisibleAncestorsAsync(storedTrack);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
@@ -459,6 +469,7 @@ public class TrackRepositoryTests
_audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10),
_audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20)
];
await SeedVisibleAncestorsAsync(storedTrack);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
@@ -496,6 +507,7 @@ public class TrackRepositoryTests
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
storedTrack.Tags = [existingTag];
storedTrack.Genres = [existingGenre];
await SeedVisibleAncestorsAsync(storedTrack);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
@@ -530,6 +542,7 @@ public class TrackRepositoryTests
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
storedTrack.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Energetic")];
storedTrack.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")];
await SeedVisibleAncestorsAsync(storedTrack);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
@@ -561,6 +574,7 @@ public class TrackRepositoryTests
{
// Arrange
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
await SeedVisibleAncestorsAsync(track);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
@@ -632,6 +646,7 @@ public class TrackRepositoryTests
TrackEntity firstDiscFirstTieTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/seven-seas-of-rhye.flac", trackNumber: 1, includeMetadata: false);
firstDiscFirstTieTrack.DiscNumber = 1;
TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/under-pressure.flac", includeMetadata: false);
await SeedVisibleAncestorsAsync(albumId, firstDiscFirstTrack.LibraryId);
_mockContext.Tracks.AddRange(secondDiscTrack, firstDiscSecondTrack, firstDiscFirstTrack, firstDiscFirstTieTrack, trackOfAnotherAlbum);
await _mockContext.SaveChangesAsync();
@@ -660,6 +675,7 @@ public class TrackRepositoryTests
secondDiscTrack.DiscNumber = 2;
TrackEntity firstDiscTrackWithoutDiscNumber = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/first-disc.flac", trackNumber: 2, includeMetadata: false);
firstDiscTrackWithoutDiscNumber.DiscNumber = null;
await SeedVisibleAncestorsAsync(albumId, firstDiscTrackWithoutDiscNumber.LibraryId);
_mockContext.Tracks.AddRange(secondDiscTrack, firstDiscTrackWithoutDiscNumber);
await _mockContext.SaveChangesAsync();
@@ -684,6 +700,7 @@ public class TrackRepositoryTests
track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")];
track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
await SeedVisibleAncestorsAsync(albumId, track.LibraryId);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
@@ -711,6 +728,7 @@ public class TrackRepositoryTests
TrackEntity firstTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/i-want-to-break-free.flac", trackNumber: 1, title: "Bohemian Rhapsody", includeMetadata: false);
firstTrack.DiscNumber = 1;
TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/a-kind-of-magic.flac", includeMetadata: false);
await SeedVisibleAncestorsAsync(albumId, firstTrack.LibraryId);
_mockContext.Tracks.AddRange(secondTrack, firstTrack, trackOfAnotherAlbum);
await _mockContext.SaveChangesAsync();
@@ -737,6 +755,7 @@ public class TrackRepositoryTests
thirdTrack.DiscNumber = 1;
TrackEntity secondTrackWithoutDiscNumber = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/second.flac", trackNumber: 2, includeMetadata: false);
secondTrackWithoutDiscNumber.DiscNumber = null;
await SeedVisibleAncestorsAsync(albumId, secondTrackWithoutDiscNumber.LibraryId);
_mockContext.Tracks.AddRange(thirdTrack, secondTrackWithoutDiscNumber);
await _mockContext.SaveChangesAsync();
@@ -771,6 +790,7 @@ public class TrackRepositoryTests
tracks[index].Contributors = [];
tracks[index].Ratings = [];
}
await SeedVisibleAncestorsAsync(albumId, tracks[0].LibraryId);
_mockContext.Tracks.AddRange(tracks);
await _mockContext.SaveChangesAsync();
@@ -796,6 +816,7 @@ public class TrackRepositoryTests
Guid albumId = Guid.NewGuid();
TrackEntity trackOfAlbum = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/youre-my-best-friend.flac", includeMetadata: false);
TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/fat-bottomed-girls.flac", includeMetadata: false);
await SeedVisibleAncestorsAsync(albumId, trackOfAlbum.LibraryId);
_mockContext.Tracks.AddRange(trackOfAlbum, trackOfAnotherAlbum);
await _mockContext.SaveChangesAsync();
@@ -818,6 +839,7 @@ public class TrackRepositoryTests
Guid albumId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/bicycle-race.flac", title: "Killer Queen", trackNumber: 9, includeMetadata: false);
track.DiscNumber = 3;
await SeedVisibleAncestorsAsync(albumId, track.LibraryId);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
@@ -843,6 +865,7 @@ public class TrackRepositoryTests
Guid albumId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/the-prophet-song.flac", includeMetadata: false);
track.DurationInSeconds = 367;
await SeedVisibleAncestorsAsync(albumId, track.LibraryId);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
@@ -866,6 +889,7 @@ public class TrackRepositoryTests
TrackEntity failedTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Failed);
TrackEntity enrichedTrack = _trackEntityFixture.Create(libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Enriched);
TrackEntity trackOfAnotherLibrary = _trackEntityFixture.Create(includeMetadata: false, metadataStatus: MetadataStatus.Pending);
await SeedVisibleAncestorsAsync(pendingTrack, failedTrack, enrichedTrack, trackOfAnotherLibrary);
_mockContext.Tracks.AddRange(pendingTrack, failedTrack, enrichedTrack, trackOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
@@ -901,6 +925,7 @@ public class TrackRepositoryTests
TrackEntity firstTrack = _trackEntityFixture.Create(includeMetadata: false);
TrackEntity secondTrack = _trackEntityFixture.Create(includeMetadata: false);
TrackEntity thirdTrack = _trackEntityFixture.Create(includeMetadata: false);
await SeedVisibleAncestorsAsync(firstTrack, secondTrack, thirdTrack);
_mockContext.Tracks.AddRange(firstTrack, secondTrack, thirdTrack);
await _mockContext.SaveChangesAsync();
@@ -921,6 +946,7 @@ public class TrackRepositoryTests
{
// Arrange
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
await SeedVisibleAncestorsAsync(track);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
@@ -985,7 +1011,10 @@ public class TrackRepositoryTests
{
// Arrange
const int TRACK_COUNT = 501;
List<TrackEntity> tracks = CreateTracks(TRACK_COUNT);
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
List<TrackEntity> tracks = CreateTracks(TRACK_COUNT, albumId, libraryId);
await SeedVisibleAncestorsAsync(albumId, libraryId);
_mockContext.Tracks.AddRange(tracks);
await _mockContext.SaveChangesAsync();
@@ -1001,14 +1030,801 @@ public class TrackRepositoryTests
result.Value.Select(track => track.Id).OrderBy(id => id));
}
[Fact]
public async Task InsertAsync_WhenATrackWithTheSamePathIsSoftDeleted_ShouldReturnTrackAlreadyExists()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
await SeedVisibleAncestorsAsync(album.Id, libraryId);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Tracks.Add(deletedTrack);
await _mockContext.SaveChangesAsync();
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false);
// Act
Result<Created> result = await _sut.InsertAsync(track, CancellationToken.None);
// Assert
// A deleted track keeps its path reserved, so a scan must never materialize the deleted file back into the catalogue.
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
}
[Fact]
public async Task GetExistingPathsAsync_WhenTrackIsSoftDeleted_ShouldStillReportItsPathAsExisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
TrackEntity deletedTrack = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Tracks.Add(deletedTrack);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyCollection<string>> result = await _sut.GetExistingPathsAsync(libraryId, ["/music/queen/deleted.flac"], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(["/music/queen/deleted.flac"], result.Value);
}
[Fact]
public async Task GetByPathAsync_WhenTrackExists_ShouldReturnIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/love-of-my-life.flac", includeMetadata: false);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await _sut.GetByPathAsync(libraryId, "/music/queen/love-of-my-life.flac", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(track.Id, result.Value!.Id);
}
[Fact]
public async Task GetByPathAsync_WhenTrackIsSoftDeleted_ShouldReturnIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
TrackEntity deletedTrack = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/deleted.flac", includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Tracks.Add(deletedTrack);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await _sut.GetByPathAsync(libraryId, "/music/queen/deleted.flac", CancellationToken.None);
// Assert
// The scan deletion strategy must be able to permanently remove a track that the user had already deleted.
Assert.False(result.IsFailure);
Assert.Equal(deletedTrack.Id, result.Value!.Id);
Assert.True(result.Value.IsDeleted);
}
[Fact]
public async Task GetByIdAsync_WhenTrackIsSoftDeleted_ShouldReturnNull()
{
// Arrange
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
await SeedVisibleAncestorsAsync(track);
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await _sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByIdAsync_WhenItsAlbumIsSoftDeleted_ShouldReturnNull()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
AlbumEntity storedAlbum = await SeedVisibleAncestorsAsync(album.Id, libraryId);
storedAlbum.IsDeleted = true;
storedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await _sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByIdAsync_WhenItsArtistIsSoftDeleted_ShouldReturnNull()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
album.IsDeleted = false;
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
album.Tracks = [track];
artist.Albums = [album];
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await _sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetByAlbumIdAsync_WhenTracksAreSoftDeleted_ShouldExcludeThem()
{
// Arrange
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false, includeMetadata: false);
await SeedVisibleAncestorsAsync(album.Id, album.LibraryId);
TrackEntity activeTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Tracks.AddRange(activeTrack, deletedTrack);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await _sut.GetByAlbumIdAsync(albumId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeTrack.Id, Assert.Single(result.Value).Id);
}
[Fact]
public async Task GetByAlbumIdAsync_WhenTheAlbumIsSoftDeleted_ShouldReturnEmpty()
{
// Arrange
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false, includeMetadata: false);
AlbumEntity storedAlbum = await SeedVisibleAncestorsAsync(album.Id, album.LibraryId);
storedAlbum.IsDeleted = true;
storedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, includeMetadata: false);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await _sut.GetByAlbumIdAsync(albumId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetByAlbumIdAsync_WhenTheArtistIsSoftDeleted_ShouldReturnEmpty()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
album.Tracks = [track];
artist.Albums = [album];
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await _sut.GetByAlbumIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task GetByAlbumIdIncludingDeletedAsync_WhenCalled_ShouldReturnActiveAndDeletedTracksOrdered()
{
// Arrange
Guid albumId = Guid.NewGuid();
TrackEntity activeTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: Guid.NewGuid(), trackNumber: 2, includeMetadata: false);
activeTrack.DiscNumber = 1;
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: activeTrack.LibraryId, trackNumber: 1, includeMetadata: false);
deletedTrack.DiscNumber = 1;
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Tracks.AddRange(activeTrack, deletedTrack);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await _sut.GetByAlbumIdIncludingDeletedAsync(albumId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([deletedTrack.Id, activeTrack.Id], result.Value.Select(track => track.Id));
}
[Fact]
public async Task GetTracksLiteByAlbumIdAsync_WhenATrackIsSoftDeleted_ShouldExcludeIt()
{
// Arrange
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, includeTracks: false, includeMetadata: false);
await SeedVisibleAncestorsAsync(album.Id, album.LibraryId);
TrackEntity activeTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: albumId, libraryId: album.LibraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Tracks.AddRange(activeTrack, deletedTrack);
await _mockContext.SaveChangesAsync();
// Act
Result<PaginatedResultDto<TrackLiteRow>> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeTrack.Id, Assert.Single(result.Value.Data).Id);
}
[Fact]
public async Task GetShuffleTracksLiteAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity visibleArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity visibleAlbum = _albumEntityFixture.Create(artistId: visibleArtist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
TrackEntity visibleTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: visibleAlbum.Id, libraryId: libraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
visibleAlbum.Tracks = [visibleTrack, deletedTrack];
visibleArtist.Albums = [visibleAlbum];
ArtistEntity artistOfDeletedAlbum = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistOfDeletedAlbum.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
deletedAlbum.Tracks = [_trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false)];
artistOfDeletedAlbum.Albums = [deletedAlbum];
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
AlbumEntity albumOfDeletedArtist = _albumEntityFixture.Create(artistId: deletedArtist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
albumOfDeletedArtist.Tracks = [_trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false)];
deletedArtist.Albums = [albumOfDeletedArtist];
_mockContext.Artists.AddRange(visibleArtist, artistOfDeletedAlbum, deletedArtist);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<ShuffleTrackRowDto>> result = await _sut.GetShuffleTracksLiteAsync(libraryId, null, null, [], 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(visibleTrack.Id, Assert.Single(result.Value).TrackId);
}
[Fact]
public async Task GetTrackStreamInfoAsync_WhenTrackIsSoftDeleted_ShouldReturnNull()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
album.Tracks = [track];
artist.Albums = [album];
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackStreamDto?> result = await _sut.GetTrackStreamInfoAsync(libraryId, album.Id, artist.Id, track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetTrackStreamInfoAsync_WhenItsAlbumIsSoftDeleted_ShouldReturnNull()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
album.Tracks = [track];
artist.Albums = [album];
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackStreamDto?> result = await _sut.GetTrackStreamInfoAsync(libraryId, album.Id, artist.Id, track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetPlaybackManifestInfoAsync_WhenItsArtistIsSoftDeleted_ShouldReturnNull()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
album.Tracks = [track];
artist.Albums = [album];
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackPlaybackManifestDto?> result = await _sut.GetPlaybackManifestInfoAsync(libraryId, album.Id, artist.Id, track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetAccessInfoByIdsAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
album.Tracks = [activeTrack, deletedTrack];
artist.Albums = [album];
_mockContext.Artists.Add(artist);
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
AlbumEntity albumOfDeletedArtist = _albumEntityFixture.Create(artistId: deletedArtist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
albumOfDeletedArtist.Artist = deletedArtist;
TrackEntity trackOfDeletedArtist = _trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false);
albumOfDeletedArtist.Tracks = [trackOfDeletedArtist];
deletedArtist.Albums = [albumOfDeletedArtist];
_mockContext.Artists.Add(deletedArtist);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackAccessSummaryDto> result = await _sut.GetAccessInfoByIdsAsync([activeTrack.Id, deletedTrack.Id, trackOfDeletedArtist.Id], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value.TrackCount);
Assert.Equal([libraryId], result.Value.LibraryIds);
}
[Fact]
public async Task GetByIdsAsync_WhenTracksOrAncestorsAreSoftDeleted_ShouldExcludeThem()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
TrackEntity activeTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
album.Tracks = [activeTrack, deletedTrack];
artist.Albums = [album];
_mockContext.Artists.Add(artist);
ArtistEntity artistOfDeletedAlbum = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistOfDeletedAlbum.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
deletedAlbum.Artist = artistOfDeletedAlbum;
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
TrackEntity trackOfDeletedAlbum = _trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false);
deletedAlbum.Tracks = [trackOfDeletedAlbum];
artistOfDeletedAlbum.Albums = [deletedAlbum];
_mockContext.Artists.Add(artistOfDeletedAlbum);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await _sut.GetByIdsAsync([activeTrack.Id, deletedTrack.Id, trackOfDeletedAlbum.Id], false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(activeTrack.Id, Assert.Single(result.Value).Id);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenTrackIsDeleted_ShouldReturnIt()
{
// Arrange
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
await SeedVisibleAncestorsAsync(track);
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await _sut.GetSoftDeletedByIdAsync(track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(track.Id, result.Value!.Id);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenItsAlbumIsDeleted_ShouldReturnNull()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
AlbumEntity storedAlbum = await SeedVisibleAncestorsAsync(album.Id, libraryId);
storedAlbum.IsDeleted = true;
storedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow.AddHours(-2);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await _sut.GetSoftDeletedByIdAsync(track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenItsArtistIsDeleted_ShouldReturnNull()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow.AddHours(-2);
album.Tracks = [track];
artist.Albums = [album];
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await _sut.GetSoftDeletedByIdAsync(track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetSoftDeletedByIdAsync_WhenTrackIsNotDeleted_ShouldReturnNull()
{
// Arrange
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
await SeedVisibleAncestorsAsync(track);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
// Act
Result<TrackEntity?> result = await _sut.GetSoftDeletedByIdAsync(track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public async Task GetSoftDeletedByLibraryIdAsync_WhenCalled_ShouldReturnOnlyVisibleDeletedTracksOrdered()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
DateTime deletedOnUtc = new(2026, 11, 14, 10, 0, 0, DateTimeKind.Utc);
TrackEntity olderDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Alpha", includeMetadata: false);
olderDeletion.IsDeleted = true;
olderDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-2);
olderDeletion.UpdatedOnUtc = deletedOnUtc;
TrackEntity newerDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Beta", includeMetadata: false);
newerDeletion.IsDeleted = true;
newerDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1);
TrackEntity sameTimeDeletion = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, title: "Gamma", includeMetadata: false);
sameTimeDeletion.IsDeleted = true;
sameTimeDeletion.DeletedOnUtc = deletedOnUtc.AddHours(-1);
album.Tracks = [olderDeletion, newerDeletion, sameTimeDeletion];
artist.Albums = [album];
_mockContext.Artists.Add(artist);
ArtistEntity deletedArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
deletedArtist.IsDeleted = true;
deletedArtist.DeletedOnUtc = deletedOnUtc.AddHours(-1);
AlbumEntity albumOfDeletedArtist = _albumEntityFixture.Create(artistId: deletedArtist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
albumOfDeletedArtist.Artist = deletedArtist;
TrackEntity hiddenDeletedTrack = _trackEntityFixture.Create(albumId: albumOfDeletedArtist.Id, libraryId: libraryId, includeMetadata: false);
hiddenDeletedTrack.IsDeleted = true;
hiddenDeletedTrack.DeletedOnUtc = deletedOnUtc;
albumOfDeletedArtist.Tracks = [hiddenDeletedTrack];
deletedArtist.Albums = [albumOfDeletedArtist];
_mockContext.Artists.Add(deletedArtist);
await _mockContext.SaveChangesAsync();
TrackEntity[] expectedDeletedTracks = [olderDeletion, newerDeletion, sameTimeDeletion];
Guid[] expectedOrder = [.. expectedDeletedTracks
.OrderByDescending(track => track.DeletedOnUtc)
.ThenByDescending(track => track.Title)
.ThenByDescending(track => track.Id)
.Select(track => track.Id)];
// Act
Result<IReadOnlyList<TrackEntity>> result = await _sut.GetSoftDeletedByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(expectedOrder, result.Value.Select(track => track.Id));
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenCalled_ShouldClearTheDeletionStateAndTime()
{
// Arrange
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(track.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.False(track.IsDeleted);
Assert.Null(track.DeletedOnUtc);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenTrackIsNotDeleted_ShouldReturnTrackNotFound()
{
// Arrange
TrackEntity track = _trackEntityFixture.Create(includeMetadata: false);
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(track.Id, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
}
[Fact]
public async Task RestoreSoftDeletedByIdAsync_WhenTrackDoesNotExist_ShouldReturnTrackNotFound()
{
// Act
Result<Updated> result = await _sut.RestoreSoftDeletedByIdAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenTrackIsSoftDeleted_ShouldReturnTrackNotFound()
{
// Arrange
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
await SeedVisibleAncestorsAsync(storedTrack);
storedTrack.IsDeleted = true;
storedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, albumId: storedTrack.AlbumId, libraryId: storedTrack.LibraryId, includeMetadata: false);
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenItsAlbumIsSoftDeleted_ShouldReturnTrackNotFound()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
AlbumEntity storedAlbum = await SeedVisibleAncestorsAsync(album.Id, libraryId);
storedAlbum.IsDeleted = true;
storedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
TrackEntity storedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, albumId: storedTrack.AlbumId, libraryId: storedTrack.LibraryId, includeMetadata: false);
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenItsArtistIsSoftDeleted_ShouldReturnTrackNotFound()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
TrackEntity storedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
_mockContext.Artists.Add(artist);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, albumId: storedTrack.AlbumId, libraryId: storedTrack.LibraryId, includeMetadata: false);
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackNotFound, result.FirstError);
}
[Fact]
public async Task UpdateAsync_WhenIncomingDeletionStateDiffers_ShouldPreserveTheActiveStateAndClearItsModifiedFlags()
{
// Arrange
TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false);
await SeedVisibleAncestorsAsync(storedTrack);
_mockContext.Tracks.Add(storedTrack);
await _mockContext.SaveChangesAsync();
TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, albumId: storedTrack.AlbumId, libraryId: storedTrack.LibraryId, includeMetadata: false);
data.Title = "Somebody to Love";
data.IsDeleted = true;
data.DeletedOnUtc = DateTime.UtcNow;
// Act
Result<Updated> result = await _sut.UpdateAsync(data, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
EntityEntry<TrackEntity> entry = _mockContext.Entry(storedTrack);
Assert.False(storedTrack.IsDeleted);
Assert.Null(storedTrack.DeletedOnUtc);
Assert.False(entry.Property(track => track.IsDeleted).IsModified);
Assert.False(entry.Property(track => track.DeletedOnUtc).IsModified);
}
[Fact]
public async Task GetTracksNeedingMetadataCountAsync_WhenATrackOrItsAncestorIsSoftDeleted_ShouldNotCountIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
album.Artist = artist;
TrackEntity pendingTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
TrackEntity deletedTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
deletedTrack.IsDeleted = true;
deletedTrack.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
album.Tracks = [pendingTrack, deletedTrack];
artist.Albums = [album];
_mockContext.Artists.Add(artist);
ArtistEntity artistOfDeletedAlbum = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity deletedAlbum = _albumEntityFixture.Create(artistId: artistOfDeletedAlbum.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
deletedAlbum.Artist = artistOfDeletedAlbum;
deletedAlbum.IsDeleted = true;
deletedAlbum.DeletedOnUtc = DateTime.UtcNow.AddHours(-1);
TrackEntity trackOfDeletedAlbum = _trackEntityFixture.Create(albumId: deletedAlbum.Id, libraryId: libraryId, includeMetadata: false, metadataStatus: MetadataStatus.Pending);
deletedAlbum.Tracks = [trackOfDeletedAlbum];
artistOfDeletedAlbum.Albums = [deletedAlbum];
_mockContext.Artists.Add(artistOfDeletedAlbum);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetTracksNeedingMetadataCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value);
}
/// <summary>
/// Creates a list of tracks with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data.
/// Seeds an active artist and the album identified by <paramref name="albumId"/>, so that the tracks of that album pass the ancestor filters of the repository.
/// </summary>
/// <param name="albumId">The Id of the album the tracks belong to.</param>
/// <param name="libraryId">The Id of the library the album belongs to.</param>
/// <returns>The seeded album, already tracked by the context.</returns>
private async Task<AlbumEntity> SeedVisibleAncestorsAsync(Guid albumId, Guid libraryId)
{
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
AlbumEntity album = _albumEntityFixture.Create(
id: albumId,
artistId: artist.Id,
libraryId: libraryId,
includeTracks: false,
includeMetadata: false);
album.Artist = artist;
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
return album;
}
/// <summary>
/// Seeds an active artist and album for each of the provided tracks, so that every track passes the ancestor filters of the repository.
/// </summary>
/// <param name="tracks">The tracks whose ancestors are seeded.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedVisibleAncestorsAsync(params TrackEntity[] tracks)
{
foreach (TrackEntity track in tracks)
await SeedVisibleAncestorsAsync(track.AlbumId, track.LibraryId);
}
/// <summary>
/// Creates a list of tracks of the provided album with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data.
/// </summary>
/// <param name="count">The number of tracks to create.</param>
/// <param name="albumId">The Id of the album that owns the tracks.</param>
/// <param name="libraryId">The Id of the library that owns the tracks.</param>
/// <returns>The created tracks.</returns>
private List<TrackEntity> CreateTracks(int count)
private List<TrackEntity> CreateTracks(int count, Guid albumId, Guid libraryId)
{
return [.. Enumerable.Range(0, count).Select(_ => _trackEntityFixture.Create(
path: $"/music/generated-{Guid.NewGuid():N}.flac", includeMetadata: false))];
albumId: albumId,
libraryId: libraryId,
path: $"/music/generated-{Guid.NewGuid():N}.flac",
includeMetadata: false))];
}
}
@@ -260,11 +260,12 @@ public class ErrorsTests
{
// Assert
// The count assertion fails when an error is added or removed, reminding to update the assertions below.
Assert.Equal(20, typeof(DomainErrors.FileSystemManagement).GetProperties().Length);
Assert.Equal(21, typeof(DomainErrors.FileSystemManagement).GetProperties().Length);
AssertError(DomainErrors.FileSystemManagement.ParentNodeCannotBeNull, ErrorType.Failure);
AssertError(DomainErrors.FileSystemManagement.PathMustBeMaximum260CharactersLong, ErrorType.Failure);
AssertError(DomainErrors.FileSystemManagement.FileCopyError, ErrorType.Failure);
AssertError(DomainErrors.FileSystemManagement.FileMoveError, ErrorType.Failure);
AssertError(DomainErrors.FileSystemManagement.FileDeleteError, ErrorType.Failure);
AssertError(DomainErrors.FileSystemManagement.DirectoryCopyError, ErrorType.Failure);
AssertError(DomainErrors.FileSystemManagement.DirectoryMoveError, ErrorType.Failure);
AssertError(DomainErrors.FileSystemManagement.FileNotFound, ErrorType.NotFound);
@@ -471,6 +471,38 @@ public class ArtistTests
Assert.Single(artist.Albums);
}
[Fact]
public void EnsureCanRemoveAlbum_WhenTheArtistHasAnotherAlbum_ShouldReturnSuccess()
{
// Arrange
Album firstAlbum = _albumFixture.Create();
Album secondAlbum = _albumFixture.Create();
Artist artist = _artistFixture.Create(albums: [firstAlbum, secondAlbum]);
// Act
Result<bool> result = artist.CanRemoveAlbum(firstAlbum);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, artist.Albums.Count);
}
[Fact]
public void EnsureCanRemoveAlbum_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnArtistMustHaveAtLeastOneAlbumError()
{
// Arrange
Album onlyAlbum = _albumFixture.Create();
Artist artist = _artistFixture.Create(albums: [onlyAlbum]);
// Act
Result<bool> result = artist.CanRemoveAlbum(onlyAlbum);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError);
Assert.Single(artist.Albums);
}
[Fact]
public void UpdateContributors_WhenCalledWithNewContributors_ShouldReplaceThemInPlace()
{
@@ -955,4 +955,42 @@ public class FileProviderServiceTests
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
_mockFileSystem.File.DidNotReceive().Delete(Arg.Any<string>());
}
[Fact]
public void DeleteFile_WhenTheFileIsLocked_ShouldReturnFileDeleteError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.Create(
s_isUnix ? "/LockedFileToDelete.txt" : @"C:\LockedFileToDelete.txt"
);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true);
_mockFileSystem.File.When(file => file.Delete(path.Path))
.Do(_ => throw new IOException("The file is locked by another process"));
// Act
Result<Deleted> result = _sut.DeleteFile(path);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileDeleteError, result.FirstError);
}
[Fact]
public void DeleteFile_WhenTheFileIsReadOnly_ShouldReturnUnauthorizedAccessError()
{
// Arrange
FileSystemPathId path = _fileSystemPathIdFixture.Create(
s_isUnix ? "/ReadOnlyFileToDelete.txt" : @"C:\ReadOnlyFileToDelete.txt"
);
_mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Delete).Returns(true);
_mockFileSystem.File.When(file => file.Delete(path.Path))
.Do(_ => throw new UnauthorizedAccessException("The file is read-only"));
// Act
Result<Deleted> result = _sut.DeleteFile(path);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Permission.UnauthorizedAccess, result.FirstError);
}
}
@@ -7,6 +7,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -772,6 +773,52 @@ public class PathServiceTests
Assert.Equal(100, result.Value.Name.Length);
}
[Fact]
public void SanitizeCompositeSegment_WhenTheNameFitsTheBudget_ShouldAppendTheIdentifier()
{
// Arrange
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
string identifier = Guid.NewGuid().ToString();
// Act
Result<PathSegment> result = _sut.SanitizeCompositeSegment("Queen", identifier);
// Assert
Assert.False(result.IsFailure);
Assert.Equal($"Queen-{identifier}", result.Value.Name);
}
[Fact]
public void SanitizeCompositeSegment_WhenTheNameExceedsTheBudget_ShouldTruncateOnlyTheName()
{
// Arrange
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
string identifier = Guid.NewGuid().ToString();
// Act
Result<PathSegment> result = _sut.SanitizeCompositeSegment(new string('a', 99), identifier);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(100, result.Value.Name.Length);
Assert.EndsWith($"-{identifier}", result.Value.Name);
Assert.Equal(new string('a', 63), result.Value.Name[..^($"-{identifier}".Length)]);
}
[Fact]
public void SanitizeCompositeSegment_WhenTheIdentifierLeavesNoRoomForTheName_ShouldReturnInvalidPath()
{
// Arrange
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
// Act
Result<PathSegment> result = _sut.SanitizeCompositeSegment("Queen", new string('a', 99));
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
}
[Fact]
public void IsPathWithin_WhenBothPathsAreValid_ShouldCreatePathIdsAndDelegateToTheStrategy()
{
@@ -76,7 +76,7 @@ public class MusicArtworkServiceTests
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -91,7 +91,7 @@ public class MusicArtworkServiceTests
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -108,7 +108,7 @@ public class MusicArtworkServiceTests
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -121,18 +121,19 @@ public class MusicArtworkServiceTests
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files"));
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle);
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
// Assert
Assert.True(result.IsFailure);
@@ -146,11 +147,12 @@ public class MusicArtworkServiceTests
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
@@ -160,7 +162,7 @@ public class MusicArtworkServiceTests
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle);
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
// Assert
Assert.False(result.IsFailure);
@@ -174,9 +176,11 @@ public class MusicArtworkServiceTests
// Arrange
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(Errors.FileSystemManagement.InvalidPath);
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(Errors.FileSystemManagement.InvalidPath);
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album");
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album");
// Assert
Assert.True(result.IsFailure);
@@ -190,7 +194,7 @@ public class MusicArtworkServiceTests
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Errors.FileSystemManagement.InvalidPath);
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album");
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album");
// Assert
Assert.True(result.IsFailure);
@@ -203,11 +207,12 @@ public class MusicArtworkServiceTests
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
byte[] uploadedBytes = [1, 2, 3, 4, 5, 6, 7, 8];
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg");
string? capturedTemporaryPath = null;
byte[]? capturedBytes = null;
@@ -227,7 +232,7 @@ public class MusicArtworkServiceTests
await using MemoryStream artworkStream = new(uploadedBytes);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -246,11 +251,12 @@ public class MusicArtworkServiceTests
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string releaseTypeName = "Single";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle, releaseTypeName);
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg");
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
@@ -263,7 +269,7 @@ public class MusicArtworkServiceTests
await using MemoryStream artworkStream = new([1, 2, 3]);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", releaseTypeName, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", releaseTypeName, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -279,10 +285,11 @@ public class MusicArtworkServiceTests
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
string? capturedTemporaryPath = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
@@ -297,7 +304,7 @@ public class MusicArtworkServiceTests
await using MemoryStream artworkStream = new([1, 2, 3, 4]);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -316,10 +323,11 @@ public class MusicArtworkServiceTests
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
string? capturedTemporaryPath = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
@@ -336,7 +344,7 @@ public class MusicArtworkServiceTests
await using MemoryStream artworkStream = new([1, 2, 3]);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, fileName!, null, CancellationToken.None);
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, fileName!, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -349,10 +357,11 @@ public class MusicArtworkServiceTests
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
byte[] uploadedBytes = [9, 8, 7, 6, 5];
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName);
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.png");
string? capturedTemporaryPath = null;
byte[]? capturedBytes = null;
@@ -372,7 +381,7 @@ public class MusicArtworkServiceTests
await using MemoryStream artworkStream = new(uploadedBytes);
// Act
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None);
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, artworkStream, "cover.png", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -390,9 +399,10 @@ public class MusicArtworkServiceTests
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName);
string? capturedTemporaryPath = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
@@ -407,7 +417,7 @@ public class MusicArtworkServiceTests
await using MemoryStream artworkStream = new([1, 2, 3]);
// Act
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None);
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, artworkStream, "cover.png", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -482,19 +492,21 @@ public class MusicArtworkServiceTests
}
[Fact]
public void DeleteStoredArtwork_WhenDeletingTheFileFails_ShouldReturnDeleted()
public void DeleteStoredArtwork_WhenDeletingTheFileFails_ShouldReturnTheError()
{
// Arrange
string artworkRelativePath = "\\media\\music\\cover.jpg";
Error error = Error.Failure("FileSystem.Error", "Failed to delete the artwork file");
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>())
.Returns(Error.Failure("FileSystem.Error", "Failed to delete the artwork file"));
.Returns(error);
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
_mockFileProviderService.Received(1).DeleteFile(Arg.Any<FileSystemPathId>());
}
@@ -510,6 +522,14 @@ public class MusicArtworkServiceTests
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
});
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.ArgAt<string>(0);
string identifier = callInfo.ArgAt<string>(1);
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
});
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
}
@@ -538,11 +558,12 @@ public class MusicArtworkServiceTests
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="albumId">The Id of the album.</param>
/// <param name="libraryName">The name of the media library the album belongs to.</param>
/// <param name="artistId">The Id of the artist of the album.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param>
/// <param name="releaseTypeName">Optional. The name of the release type directory the album is stored under.</param>
/// <returns>The expected file system path of the album artwork directory.</returns>
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null)
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, string? releaseTypeName = null)
{
if (string.IsNullOrWhiteSpace(releaseTypeName))
{
@@ -551,7 +572,7 @@ public class MusicArtworkServiceTests
"media",
"music",
$"{libraryName}-{libraryId}",
artistName,
$"{artistName}-{artistId}",
$"{albumTitle}-{albumId}");
}
@@ -560,7 +581,7 @@ public class MusicArtworkServiceTests
"media",
"music",
$"{libraryName}-{libraryId}",
artistName,
$"{artistName}-{artistId}",
releaseTypeName,
$"{albumTitle}-{albumId}");
}
@@ -570,15 +591,16 @@ public class MusicArtworkServiceTests
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
/// <param name="artistName">The name of the artist.</param>
/// <returns>The expected file system path of the artist artwork directory.</returns>
private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName)
private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, Guid artistId, string artistName)
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"music",
$"{libraryName}-{libraryId}",
artistName);
$"{artistName}-{artistId}");
}
}
@@ -236,6 +236,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests
await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync(
_libraryId.Value,
Arg.Any<string>(),
artist.Id,
artist.Name,
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
Arg.Any<CancellationToken>());
@@ -269,6 +270,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests
_libraryId.Value,
album.Id,
Arg.Any<string>(),
album.ArtistId,
Arg.Any<string>(),
album.Title,
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
@@ -328,7 +330,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
SetupArtists(artist);
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Artwork.Error", "Failed to store the artwork"));
// Act
@@ -347,7 +349,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
SetupArtists(artist);
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>())
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>())
.Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork files"));
// Act
@@ -551,12 +553,12 @@ public class MusicMediaLibraryScanArtworkEnricherTests
/// </summary>
private void SetupSuccessArtworkStorage()
{
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("/media/music/cover.jpg"));
_mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
_mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From("/media/music/cover.jpg"));
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>()).Returns(Result.Deleted);
_mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>()).Returns(Result.Deleted);
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>()).Returns(Result.Deleted);
_mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>()).Returns(Result.Deleted);
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockMusicArtworkRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockFileHashService.ComputeFileHash(Arg.Any<string>()).Returns(123UL);
@@ -165,6 +165,8 @@ public class BookArtworkServiceTests
// Arrange
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(Errors.FileSystemManagement.InvalidPath);
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(Errors.FileSystemManagement.InvalidPath);
// Act
Result<Deleted> result = _sut.DeleteBookArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title");
@@ -192,6 +194,14 @@ public class BookArtworkServiceTests
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
});
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.ArgAt<string>(0);
string identifier = callInfo.ArgAt<string>(1);
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
});
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
@@ -0,0 +1,199 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetDeletedAlbums;
using Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
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;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedAlbumsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedAlbumsEndpointTests
{
private readonly IQueryHandler<GetDeletedAlbumsQuery, Result<IReadOnlyList<DeletedAlbumResponse>>> _mockHandler;
private readonly GetDeletedAlbumsEndpoint _sut;
private readonly DeletedAlbumResponseFixture _deletedAlbumResponseFixture = new();
private readonly GetDeletedAlbumsQueryFixture _getDeletedAlbumsQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedAlbumsEndpointTests"/> class.
/// </summary>
public GetDeletedAlbumsEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetDeletedAlbumsQuery, Result<IReadOnlyList<DeletedAlbumResponse>>>>();
_sut = FastEndpoints.Factory.Create<GetDeletedAlbumsEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeletedAlbums()
{
// Arrange
Guid libraryId = Guid.NewGuid();
IReadOnlyList<DeletedAlbumResponse> expectedAlbums =
[
_deletedAlbumResponseFixture.Create(
libraryId: libraryId,
artistName: "Queen",
title: "A Night at the Opera",
includeCoverPath: false)
];
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedAlbums));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<IReadOnlyList<DeletedAlbumResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<DeletedAlbumResponse>>>(result);
Assert.Equal(expectedAlbums, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<GetDeletedAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = DomainErrors.Library.LibraryIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetDeletedAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteLibraryIdToTheHandler()
{
// Arrange
Guid libraryId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<DeletedAlbumResponse>>([]));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
GetDeletedAlbumsQuery expectedQuery = _getDeletedAlbumsQueryFixture.Create(libraryId: libraryId.ToString());
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<DeletedAlbumResponse>>([]));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
GetDeletedAlbumsQuery expectedQuery = _getDeletedAlbumsQueryFixture.Create(libraryId: "not-a-library-guid");
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<DeletedAlbumResponse>>([]));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
GetDeletedAlbumsQuery expectedQuery = _getDeletedAlbumsQueryFixture.Create(includeLibraryId: false);
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetDeletedAlbumsQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From<IReadOnlyList<DeletedAlbumResponse>>([]);
}, callInfo.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,238 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.RestoreAlbum;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum;
/// <summary>
/// Contains unit tests for the <see cref="RestoreAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreAlbumEndpointTests
{
private readonly ICommandHandler<RestoreAlbumCommand, Result<Updated>> _mockHandler;
private readonly RestoreAlbumEndpoint _sut;
private readonly RestoreAlbumCommandFixture _restoreAlbumCommandFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreAlbumEndpointTests"/> class.
/// </summary>
public RestoreAlbumEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<RestoreAlbumCommand, Result<Updated>>>();
_sut = FastEndpoints.Factory.Create<RestoreAlbumEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreAlbumCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<Updated> okResult = Assert.IsType<Ok<Updated>>(result);
Assert.Equal(Result.Updated, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Music.AlbumNotFound;
_mockHandler.HandleAsync(Arg.Any<RestoreAlbumCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("AlbumNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<RestoreAlbumCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = DomainErrors.Music.AlbumIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<RestoreAlbumCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteIdsToTheHandler()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreAlbumCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
RestoreAlbumCommand expectedCommand = _restoreAlbumCommandFixture.Create(
libraryId: libraryId.ToString(),
artistId: artistId.ToString(),
albumId: albumId.ToString());
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreAlbumCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid";
_sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
RestoreAlbumCommand expectedCommand = _restoreAlbumCommandFixture.Create(
libraryId: "not-a-library-guid",
artistId: "not-an-artist-guid",
albumId: "not-an-album-guid");
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreAlbumCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("artistId");
_sut.HttpContext.Request.RouteValues.Remove("albumId");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
RestoreAlbumCommand expectedCommand = _restoreAlbumCommandFixture.Create(
includeLibraryId: false,
includeArtistId: false,
includeAlbumId: false);
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<RestoreAlbumCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Updated);
}, callInfo.Arg<CancellationToken>()));
ConfigureRouteValues();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Configures the route values of a valid restore request.
/// </summary>
private void ConfigureRouteValues()
{
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString();
}
}
@@ -0,0 +1,198 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetDeletedArtists;
using Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
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;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedArtistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedArtistsEndpointTests
{
private readonly IQueryHandler<GetDeletedArtistsQuery, Result<IReadOnlyList<DeletedArtistResponse>>> _mockHandler;
private readonly GetDeletedArtistsEndpoint _sut;
private readonly DeletedArtistResponseFixture _deletedArtistResponseFixture = new();
private readonly GetDeletedArtistsQueryFixture _getDeletedArtistsQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedArtistsEndpointTests"/> class.
/// </summary>
public GetDeletedArtistsEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetDeletedArtistsQuery, Result<IReadOnlyList<DeletedArtistResponse>>>>();
_sut = FastEndpoints.Factory.Create<GetDeletedArtistsEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeletedArtists()
{
// Arrange
Guid libraryId = Guid.NewGuid();
IReadOnlyList<DeletedArtistResponse> expectedArtists =
[
_deletedArtistResponseFixture.Create(
libraryId: libraryId,
name: "Queen",
includeCoverPath: false)
];
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedArtists));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<IReadOnlyList<DeletedArtistResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<DeletedArtistResponse>>>(result);
Assert.Equal(expectedArtists, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<GetDeletedArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = DomainErrors.Library.LibraryIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetDeletedArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteLibraryIdToTheHandler()
{
// Arrange
Guid libraryId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<DeletedArtistResponse>>([]));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
GetDeletedArtistsQuery expectedQuery = _getDeletedArtistsQueryFixture.Create(libraryId: libraryId.ToString());
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<DeletedArtistResponse>>([]));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
GetDeletedArtistsQuery expectedQuery = _getDeletedArtistsQueryFixture.Create(libraryId: "not-a-library-guid");
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<DeletedArtistResponse>>([]));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
GetDeletedArtistsQuery expectedQuery = _getDeletedArtistsQueryFixture.Create(includeLibraryId: false);
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetDeletedArtistsQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From<IReadOnlyList<DeletedArtistResponse>>([]);
}, callInfo.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,228 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.RestoreArtist;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist;
/// <summary>
/// Contains unit tests for the <see cref="RestoreArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreArtistEndpointTests
{
private readonly ICommandHandler<RestoreArtistCommand, Result<Updated>> _mockHandler;
private readonly RestoreArtistEndpoint _sut;
private readonly RestoreArtistCommandFixture _restoreArtistCommandFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreArtistEndpointTests"/> class.
/// </summary>
public RestoreArtistEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<RestoreArtistCommand, Result<Updated>>>();
_sut = FastEndpoints.Factory.Create<RestoreArtistEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<Updated> okResult = Assert.IsType<Ok<Updated>>(result);
Assert.Equal(Result.Updated, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Music.ArtistNotFound;
_mockHandler.HandleAsync(Arg.Any<RestoreArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("ArtistNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<RestoreArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = DomainErrors.Music.ArtistIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<RestoreArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "ArtistIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteIdsToTheHandler()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
RestoreArtistCommand expectedCommand = _restoreArtistCommandFixture.Create(
libraryId: libraryId.ToString(),
artistId: artistId.ToString());
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
RestoreArtistCommand expectedCommand = _restoreArtistCommandFixture.Create(
libraryId: "not-a-library-guid",
artistId: "not-an-artist-guid");
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("artistId");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
RestoreArtistCommand expectedCommand = _restoreArtistCommandFixture.Create(includeLibraryId: false, includeArtistId: false);
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<RestoreArtistCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Updated);
}, callInfo.Arg<CancellationToken>()));
ConfigureRouteValues();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Configures the route values of a valid restore request.
/// </summary>
private void ConfigureRouteValues()
{
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString();
}
}
@@ -0,0 +1,199 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetDeletedTracks;
using Lumina.Contracts.Fixtures.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
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;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks;
/// <summary>
/// Contains unit tests for the <see cref="GetDeletedTracksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedTracksEndpointTests
{
private readonly IQueryHandler<GetDeletedTracksQuery, Result<IReadOnlyList<DeletedTrackResponse>>> _mockHandler;
private readonly GetDeletedTracksEndpoint _sut;
private readonly DeletedTrackResponseFixture _deletedTrackResponseFixture = new();
private readonly GetDeletedTracksQueryFixture _getDeletedTracksQueryFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedTracksEndpointTests"/> class.
/// </summary>
public GetDeletedTracksEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetDeletedTracksQuery, Result<IReadOnlyList<DeletedTrackResponse>>>>();
_sut = FastEndpoints.Factory.Create<GetDeletedTracksEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeletedTracks()
{
// Arrange
Guid libraryId = Guid.NewGuid();
IReadOnlyList<DeletedTrackResponse> expectedTracks =
[
_deletedTrackResponseFixture.Create(
libraryId: libraryId,
artistName: "Queen",
albumTitle: "A Night at the Opera",
title: "Bohemian Rhapsody")
];
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedTracksQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedTracks));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<IReadOnlyList<DeletedTrackResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<DeletedTrackResponse>>>(result);
Assert.Equal(expectedTracks, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<GetDeletedTracksQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = DomainErrors.Library.LibraryIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<GetDeletedTracksQuery>(), Arg.Any<CancellationToken>())
.Returns(validationError);
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteLibraryIdToTheHandler()
{
// Arrange
Guid libraryId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedTracksQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<DeletedTrackResponse>>([]));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
GetDeletedTracksQuery expectedQuery = _getDeletedTracksQueryFixture.Create(libraryId: libraryId.ToString());
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedTracksQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<DeletedTrackResponse>>([]));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
GetDeletedTracksQuery expectedQuery = _getDeletedTracksQueryFixture.Create(libraryId: "not-a-library-guid");
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetDeletedTracksQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<DeletedTrackResponse>>([]));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
GetDeletedTracksQuery expectedQuery = _getDeletedTracksQueryFixture.Create(includeLibraryId: false);
await _mockHandler.Received(1).HandleAsync(expectedQuery, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetDeletedTracksQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From<IReadOnlyList<DeletedTrackResponse>>([]);
}, callInfo.Arg<CancellationToken>()));
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,246 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.RestoreTrack;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack;
/// <summary>
/// Contains unit tests for the <see cref="RestoreTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreTrackEndpointTests
{
private readonly ICommandHandler<RestoreTrackCommand, Result<Updated>> _mockHandler;
private readonly RestoreTrackEndpoint _sut;
private readonly RestoreTrackCommandFixture _restoreTrackCommandFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreTrackEndpointTests"/> class.
/// </summary>
public RestoreTrackEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<RestoreTrackCommand, Result<Updated>>>();
_sut = FastEndpoints.Factory.Create<RestoreTrackEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdated()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreTrackCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
Ok<Updated> okResult = Assert.IsType<Ok<Updated>>(result);
Assert.Equal(Result.Updated, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = DomainErrors.Music.TrackNotFound;
_mockHandler.HandleAsync(Arg.Any<RestoreTrackCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
Assert.Equal("General.NotFound", problemDetailsBody.Title);
Assert.Equal("TrackNotFound", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
_mockHandler.HandleAsync(Arg.Any<RestoreTrackCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
ProblemDetails problemDetailsBody = Assert.IsType<ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
Error validationError = DomainErrors.Music.TrackIdCannotBeEmpty;
_mockHandler.HandleAsync(Arg.Any<RestoreTrackCommand>(), Arg.Any<CancellationToken>())
.Returns(validationError);
ConfigureRouteValues();
// Act
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "TrackIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendTheRouteIdsToTheHandler()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreTrackCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString();
_sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString();
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
RestoreTrackCommand expectedCommand = _restoreTrackCommandFixture.Create(
libraryId: libraryId.ToString(),
artistId: artistId.ToString(),
albumId: albumId.ToString(),
trackId: trackId.ToString());
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreTrackCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
_sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid";
_sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid";
_sut.HttpContext.Request.RouteValues["trackId"] = "not-a-track-guid";
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
RestoreTrackCommand expectedCommand = _restoreTrackCommandFixture.Create(
libraryId: "not-a-library-guid",
artistId: "not-an-artist-guid",
albumId: "not-an-album-guid",
trackId: "not-a-track-guid");
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<RestoreTrackCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
_sut.HttpContext.Request.RouteValues.Remove("artistId");
_sut.HttpContext.Request.RouteValues.Remove("albumId");
_sut.HttpContext.Request.RouteValues.Remove("trackId");
// Act
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
// Assert
RestoreTrackCommand expectedCommand = _restoreTrackCommandFixture.Create(
includeLibraryId: false,
includeArtistId: false,
includeAlbumId: false,
includeTrackId: false);
await _mockHandler.Received(1).HandleAsync(expectedCommand, Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<RestoreTrackCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Updated);
}, callInfo.Arg<CancellationToken>()));
ConfigureRouteValues();
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
/// <summary>
/// Configures the route values of a valid restore request.
/// </summary>
private void ConfigureRouteValues()
{
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString();
_sut.HttpContext.Request.RouteValues["trackId"] = Guid.NewGuid().ToString();
}
}
@@ -0,0 +1,225 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreMusicAlbum;
/// <summary>
/// Contains unit tests for the <see cref="RestoreMusicAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicAlbumEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly RestoreMusicAlbumEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicAlbumEndpointTests"/> class.
/// </summary>
public RestoreMusicAlbumEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
// The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about
// cancellation focus on the URL construction instead of repeating the upstream stub.
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(new Web.Common.Requests.Common.EmptyRequest());
_sut = Factory.Create<RestoreMusicAlbumEndpoint>(_mockApiHttpClient);
}
[Theory]
[InlineData("D")] // Standard hyphenated format.
[InlineData("B")] // Braced format.
[InlineData("N")] // Compact format.
[InlineData("P")] // Parenthesized format.
public async Task ExecuteAsync_WhenCalled_ShouldRestoreAlbumViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat)
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(guidFormat), albumId.ToString(guidFormat), libraryId.ToString(guidFormat));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, albumId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest("not-a-guid", albumId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(null, albumId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), "not-a-guid", libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAlbumRouteIdIsMissing_ShouldForwardGuidEmptyAlbumIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), null, libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), "not-a-guid");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId, albumId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), null);
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId, albumId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), libraryId.ToString());
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(Task.FromCanceled<Web.Common.Requests.Common.EmptyRequest>(cancellationTokenSource.Token));
// Act & Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token));
}
/// <summary>
/// Sets the route and query values the endpoint reads the album identity from.
/// </summary>
/// <param name="artistId">The raw route value of the artist Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="albumId">The raw route value of the album Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="libraryId">The raw query value of the library Id, or <see langword="null"/> to leave the query string missing.</param>
private void ConfigureRequest(string? artistId, string? albumId, string? libraryId)
{
if (artistId is not null)
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
if (albumId is not null)
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
if (libraryId is not null)
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
}
/// <summary>
/// Builds the upstream endpoint the album restoration is expected to be sent to.
/// </summary>
/// <param name="libraryId">The normalized Id of the media library.</param>
/// <param name="artistId">The normalized Id of the artist.</param>
/// <param name="albumId">The normalized Id of the album.</param>
/// <returns>The expected upstream endpoint.</returns>
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId)
{
return ApiRoutes.Music.RESTORE_ALBUM
.Replace("{libraryId}", libraryId.ToString())
.Replace("{artistId}", artistId.ToString())
.Replace("{albumId}", albumId.ToString());
}
}
@@ -91,6 +91,7 @@ public class MusicArtistsIndexViewEndpointTests
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, Arg.Any<object>()).Returns("http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.DELETE_ARTIST, Arg.Any<object>()).Returns("http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000/api-delete-artist");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.DELETED_MUSIC_ITEMS).Returns("http://localhost/en-us/library/audio-library/music-library/deleted-items");
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
@@ -120,6 +121,10 @@ public class MusicArtistsIndexViewEndpointTests
string.Equals(
page.PageData["deleteUrl"] as string,
"http://localhost/en-us/library/audio-library/music-library/artists/00000000-0000-0000-0000-000000000000/api-delete-artist",
StringComparison.Ordinal) &&
string.Equals(
page.PageData["deletedItemsUrl"] as string,
"http://localhost/en-us/library/audio-library/music-library/deleted-items",
StringComparison.Ordinal)),
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
Arg.Any<CancellationToken>());
@@ -0,0 +1,178 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreMusicArtist;
/// <summary>
/// Contains unit tests for the <see cref="RestoreMusicArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicArtistEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly RestoreMusicArtistEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicArtistEndpointTests"/> class.
/// </summary>
public RestoreMusicArtistEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
// The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about
// cancellation focus on the URL construction instead of repeating the upstream stub.
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(new Web.Common.Requests.Common.EmptyRequest());
_sut = Factory.Create<RestoreMusicArtistEndpoint>(_mockApiHttpClient);
}
[Theory]
[InlineData("D")] // Standard hyphenated format.
[InlineData("B")] // Braced format.
[InlineData("N")] // Compact format.
[InlineData("P")] // Parenthesized format.
public async Task ExecuteAsync_WhenCalled_ShouldRestoreArtistViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat)
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(guidFormat), libraryId.ToString(guidFormat));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ConfigureRequest("not-a-guid", libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ConfigureRequest(null, libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), "not-a-guid");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), null);
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), libraryId.ToString());
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(Task.FromCanceled<Web.Common.Requests.Common.EmptyRequest>(cancellationTokenSource.Token));
// Act & Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token));
}
/// <summary>
/// Sets the route and query values the endpoint reads the artist identity from.
/// </summary>
/// <param name="artistId">The raw route value of the artist Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="libraryId">The raw query value of the library Id, or <see langword="null"/> to leave the query string missing.</param>
private void ConfigureRequest(string? artistId, string? libraryId)
{
if (artistId is not null)
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
if (libraryId is not null)
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
}
/// <summary>
/// Builds the upstream endpoint the artist restoration is expected to be sent to.
/// </summary>
/// <param name="libraryId">The normalized Id of the media library.</param>
/// <param name="artistId">The normalized Id of the artist.</param>
/// <returns>The expected upstream endpoint.</returns>
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId)
{
return ApiRoutes.Music.RESTORE_ARTIST
.Replace("{libraryId}", libraryId.ToString())
.Replace("{artistId}", artistId.ToString());
}
}
@@ -0,0 +1,345 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.DeletedMusicItems;
/// <summary>
/// Contains unit tests for the <see cref="DeletedMusicItemsViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedMusicItemsViewEndpointTests
{
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
private readonly IApiHttpClient _mockApiHttpClient;
private readonly IUrlService _mockUrlService;
private readonly ThemePageRenderer _mockThemePageRenderer;
private readonly IAntiforgery _mockAntiforgery;
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly DeletedMusicItemsViewEndpoint _sut;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
private readonly DeletedMusicArtistDtoFixture _deletedMusicArtistDtoFixture = new();
private readonly DeletedMusicAlbumDtoFixture _deletedMusicAlbumDtoFixture = new();
private readonly DeletedMusicTrackDtoFixture _deletedMusicTrackDtoFixture = new();
private readonly DeletedMusicItemsPageDtoFixture _deletedMusicItemsPageDtoFixture = new();
private readonly GetMusicArtistsViewRequestFixture _getMusicArtistsViewRequestFixture = new();
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
private readonly List<object?> _artistRestoreRouteValues = [];
private readonly List<object?> _albumRestoreRouteValues = [];
private readonly List<object?> _trackRestoreRouteValues = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeletedMusicItemsViewEndpointTests"/> class.
/// </summary>
public DeletedMusicItemsViewEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_mockUrlService = Substitute.For<IUrlService>();
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
_mockAntiforgery = Substitute.For<IAntiforgery>();
_mockAntiforgery.GetAndStoreTokens(Arg.Any<HttpContext>())
.Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken"));
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(
callInfo.Arg<string>(),
callInfo.Arg<string>() == "Title" ? "Deleted items" : $"Localized-{callInfo.Arg<string>()}"));
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(
[
new("Title", "Deleted items"),
new("BackToLibrary", "Back to library"),
new("NoDeletedItems", "There are no deleted items in this library."),
new("Artists", "Artists"),
new("Albums", "Albums"),
new("Tracks", "Tracks"),
new("Name", "Name"),
new("Artist", "Artist"),
new("Album", "Album"),
new("TrackTitle", "Title"),
new("DeletedOn", "Deleted on"),
new("Restore", "Restore"),
new("Restored", "The item was restored."),
new("RestoreFailed", "The item could not be restored.")
]);
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
_sut = Factory.Create<DeletedMusicItemsViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory);
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
_sut.HttpContext.Request.Path = "/en-us/library/audio-library/music-library/deleted-items";
StubUrls();
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData()
{
// Arrange
LibraryDto library = _libraryDtoFixture.Create(title: "Music");
DeletedMusicArtistDto[] deletedArtists = [.. _deletedMusicArtistDtoFixture.CreateMany(2)];
DeletedMusicAlbumDto[] deletedAlbums = [.. _deletedMusicAlbumDtoFixture.CreateMany(2)];
DeletedMusicTrackDto[] deletedTracks = [.. _deletedMusicTrackDtoFixture.CreateMany(2)];
Guid libraryId = library.Id!.Value;
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
_mockApiHttpClient.GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedArtists);
_mockApiHttpClient.GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedAlbums);
_mockApiHttpClient.GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedTracks);
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>deleted</section>", script: "<script>deleted</script>")));
// Act
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: libraryId), CancellationToken.None);
// Assert
Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result));
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", libraryId.ToString())),
Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<DeletedMusicArtistDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_ARTISTS.Replace("{libraryId}", libraryId.ToString())),
Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<DeletedMusicAlbumDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_ALBUMS.Replace("{libraryId}", libraryId.ToString())),
Arg.Any<CancellationToken>());
await _mockApiHttpClient.Received(1).GetAsync<DeletedMusicTrackDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Music.GET_DELETED_TRACKS.Replace("{libraryId}", libraryId.ToString())),
Arg.Any<CancellationToken>());
await _mockThemePageRenderer.Received(1).RenderAsync(
Arg.Is<ThemePageDto>(page =>
page.PageKey == "library/audio-library/music-library/deleted-items" &&
page.Title == "Deleted items" &&
page.Description == string.Empty &&
string.Equals(page.PageData["libraryId"] as string, libraryId.ToString(), StringComparison.Ordinal) &&
string.Equals(page.PageData["libraryTitle"] as string, "Music", StringComparison.Ordinal) &&
string.Equals(page.PageData["artistRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/api-restore-artist", StringComparison.Ordinal) &&
string.Equals(page.PageData["albumRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/api-restore-album", StringComparison.Ordinal) &&
string.Equals(page.PageData["trackRestoreUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/{ZERO_GUID}/api-restore-track", StringComparison.Ordinal) &&
string.Equals(page.PageData["backUrl"] as string, $"http://localhost/en-us/library/audio-library/music-library/artists?libraryId={libraryId}", StringComparison.Ordinal) &&
string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal) &&
HasDocumentedDeletedMusicItems(page, deletedArtists, deletedAlbums, deletedTracks) &&
HasDocumentedLocalizedStrings(page)),
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
Arg.Any<CancellationToken>());
_mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext);
}
[Fact]
public async Task ExecuteAsync_WhenLibraryIdIsNull_ShouldRedirectToHome()
{
// Arrange
_mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us");
// Act
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: null), CancellationToken.None);
// Assert
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
Assert.Equal("http://localhost/en-us", redirectResult.Url);
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockApiHttpClient.DidNotReceive().GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockApiHttpClient.DidNotReceive().GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockApiHttpClient.DidNotReceive().GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
_mockAntiforgery.DidNotReceive().GetAndStoreTokens(Arg.Any<HttpContext>());
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheDeletedMusicItems()
{
// Arrange
LibraryDto library = _libraryDtoFixture.Create(title: "Music");
DeletedMusicArtistDto[] deletedArtists = [.. _deletedMusicArtistDtoFixture.CreateMany(2)];
DeletedMusicAlbumDto[] deletedAlbums = [.. _deletedMusicAlbumDtoFixture.CreateMany(2)];
DeletedMusicTrackDto[] deletedTracks = [.. _deletedMusicTrackDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
_mockApiHttpClient.GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedArtists);
_mockApiHttpClient.GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedAlbums);
_mockApiHttpClient.GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(deletedTracks);
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
// Act
IResult result = await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
// Assert
Assert.Equal("/Core/Views/Library/AudioLibrary/MusicLibrary/DeletedItems.cshtml", GetRenderedViewName(result));
DeletedMusicItemsPageDto expectedPage = _deletedMusicItemsPageDtoFixture.Create(
library: library,
deletedArtists: deletedArtists,
deletedAlbums: deletedAlbums,
deletedTracks: deletedTracks);
DeletedMusicItemsPageDto model = Assert.IsType<DeletedMusicItemsPageDto>(GetRenderedModel(result));
Assert.Equal(expectedPage, model);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldUseTheAllZeroGuidTemplatesOfTheRestoreRoutes()
{
// Arrange
LibraryDto library = _libraryDtoFixture.Create(title: "Music");
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(library);
_mockApiHttpClient.GetAsync<DeletedMusicArtistDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Array.Empty<DeletedMusicArtistDto>());
_mockApiHttpClient.GetAsync<DeletedMusicAlbumDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Array.Empty<DeletedMusicAlbumDto>());
_mockApiHttpClient.GetAsync<DeletedMusicTrackDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Array.Empty<DeletedMusicTrackDto>());
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
// Act
await _sut.ExecuteAsync(_getMusicArtistsViewRequestFixture.Create(libraryId: library.Id), CancellationToken.None);
// Assert
// The themed page replaces each all-zero Guid placeholder of the restore URLs one at a time, so every route value must be an empty Guid.
Assert.Single(_artistRestoreRouteValues);
AssertRouteValueIsEmptyGuid(_artistRestoreRouteValues[0], "artistId");
Assert.Single(_albumRestoreRouteValues);
AssertRouteValueIsEmptyGuid(_albumRestoreRouteValues[0], "artistId");
AssertRouteValueIsEmptyGuid(_albumRestoreRouteValues[0], "albumId");
Assert.Single(_trackRestoreRouteValues);
AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "artistId");
AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "albumId");
AssertRouteValueIsEmptyGuid(_trackRestoreRouteValues[0], "trackId");
}
/// <summary>
/// Stubs the absolute URLs that the endpoint resolves for the deleted music items page.
/// </summary>
private void StubUrls()
{
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.ARTISTS_INDEX).Returns("http://localhost/en-us/library/audio-library/music-library/artists");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_ARTIST, Arg.Any<object?>())
.Returns(callInfo =>
{
_artistRestoreRouteValues.Add(callInfo.ArgAt<object?>(1));
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/api-restore-artist";
});
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_ALBUM, Arg.Any<object?>())
.Returns(callInfo =>
{
_albumRestoreRouteValues.Add(callInfo.ArgAt<object?>(1));
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/api-restore-album";
});
_mockUrlService.GetAbsoluteUrl(WebRoutes.Music.RESTORE_TRACK, Arg.Any<object?>())
.Returns(callInfo =>
{
_trackRestoreRouteValues.Add(callInfo.ArgAt<object?>(1));
return $"http://localhost/en-us/library/audio-library/music-library/artists/{ZERO_GUID}/albums/{ZERO_GUID}/tracks/{ZERO_GUID}/api-restore-track";
});
}
/// <summary>
/// Reads the private view name of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
/// </summary>
/// <param name="result">The result returned by the endpoint under test.</param>
/// <returns>The name or path of the rendered view.</returns>
private static string GetRenderedViewName(IResult result)
{
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(viewNameField);
return (string)viewNameField.GetValue(viewResult)!;
}
/// <summary>
/// Reads the private model of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
/// </summary>
/// <param name="result">The result returned by the endpoint under test.</param>
/// <returns>The model passed to the rendered view.</returns>
private static object? GetRenderedModel(IResult result)
{
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(modelField);
return modelField.GetValue(viewResult);
}
/// <summary>
/// Determines whether the page data carries the serialized deleted music items of the page.
/// </summary>
/// <param name="page">The page model passed to the theme renderer.</param>
/// <param name="deletedArtists">The deleted artists expected in the page data.</param>
/// <param name="deletedAlbums">The deleted albums expected in the page data.</param>
/// <param name="deletedTracks">The deleted tracks expected in the page data.</param>
/// <returns><see langword="true"/> when the serialized deleted items match the expected ones; otherwise <see langword="false"/>.</returns>
private static bool HasDocumentedDeletedMusicItems(
ThemePageDto page,
DeletedMusicArtistDto[] deletedArtists,
DeletedMusicAlbumDto[] deletedAlbums,
DeletedMusicTrackDto[] deletedTracks)
{
if (!page.PageData.TryGetValue("deletedArtistsJson", out object? artistsValue) || artistsValue is not string artistsJson)
return false;
if (!page.PageData.TryGetValue("deletedAlbumsJson", out object? albumsValue) || albumsValue is not string albumsJson)
return false;
if (!page.PageData.TryGetValue("deletedTracksJson", out object? tracksValue) || tracksValue is not string tracksJson)
return false;
using JsonDocument artistsDocument = JsonDocument.Parse(artistsJson);
using JsonDocument albumsDocument = JsonDocument.Parse(albumsJson);
using JsonDocument tracksDocument = JsonDocument.Parse(tracksJson);
return artistsDocument.RootElement.GetArrayLength() == deletedArtists.Length
&& string.Equals(artistsDocument.RootElement[0].GetProperty("name").GetString(), deletedArtists[0].Name, StringComparison.Ordinal)
&& albumsDocument.RootElement.GetArrayLength() == deletedAlbums.Length
&& string.Equals(albumsDocument.RootElement[0].GetProperty("title").GetString(), deletedAlbums[0].Title, StringComparison.Ordinal)
&& tracksDocument.RootElement.GetArrayLength() == deletedTracks.Length
&& string.Equals(tracksDocument.RootElement[0].GetProperty("albumTitle").GetString(), deletedTracks[0].AlbumTitle, StringComparison.Ordinal);
}
/// <summary>
/// Determines whether the page data carries the localized strings of the deleted music items page, both raw and serialized.
/// </summary>
/// <param name="page">The page model passed to the theme renderer.</param>
/// <returns><see langword="true"/> when the localized strings are exposed and serialized; otherwise <see langword="false"/>.</returns>
private static bool HasDocumentedLocalizedStrings(ThemePageDto page)
{
if (!page.PageData.TryGetValue("strings", out object? value) || value is not Dictionary<string, object?> strings)
return false;
if (!page.PageData.TryGetValue("stringsJson", out object? jsonValue) || jsonValue is not string stringsJson)
return false;
using JsonDocument stringsDocument = JsonDocument.Parse(stringsJson);
return string.Equals(strings["Title"] as string, "Deleted items", StringComparison.Ordinal)
&& string.Equals(strings["NoDeletedItems"] as string, "There are no deleted items in this library.", StringComparison.Ordinal)
&& string.Equals(stringsDocument.RootElement.GetProperty("title").GetString(), "Deleted items", StringComparison.Ordinal)
&& string.Equals(stringsDocument.RootElement.GetProperty("noDeletedItems").GetString(), "There are no deleted items in this library.", StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the named property of an anonymous route values object is the empty Guid.
/// </summary>
/// <param name="routeValues">The anonymous route values object passed to the URL service.</param>
/// <param name="propertyName">The name of the route value property to check.</param>
private static void AssertRouteValueIsEmptyGuid(object? routeValues, string propertyName)
{
Assert.NotNull(routeValues);
PropertyInfo? property = routeValues!.GetType().GetProperty(propertyName);
Assert.NotNull(property);
Assert.Equal(Guid.Empty, (Guid)property!.GetValue(routeValues)!);
}
}
@@ -0,0 +1,276 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreMusicTrack;
/// <summary>
/// Contains unit tests for the <see cref="RestoreMusicTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreMusicTrackEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly RestoreMusicTrackEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreMusicTrackEndpointTests"/> class.
/// </summary>
public RestoreMusicTrackEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
// The restore endpoints forward a bodyless POST upstream; returning an empty request lets every test that is not about
// cancellation focus on the URL construction instead of repeating the upstream stub.
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(new Web.Common.Requests.Common.EmptyRequest());
_sut = Factory.Create<RestoreMusicTrackEndpoint>(_mockApiHttpClient);
}
[Theory]
[InlineData("D")] // Standard hyphenated format.
[InlineData("B")] // Braced format.
[InlineData("N")] // Compact format.
[InlineData("P")] // Parenthesized format.
public async Task ExecuteAsync_WhenCalled_ShouldRestoreTrackViaApiWithNormalizedIdsAndReturnSuccessPayload(string guidFormat)
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(guidFormat), albumId.ToString(guidFormat), trackId.ToString(guidFormat), libraryId.ToString(guidFormat));
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, albumId, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isRestored").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsNotParseable_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest("not-a-guid", albumId.ToString(), trackId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenArtistRouteIdIsMissing_ShouldForwardGuidEmptyArtistIdToApi()
{
// Arrange
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(null, albumId.ToString(), trackId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, Guid.Empty, albumId, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAlbumRouteIdIsNotParseable_ShouldForwardGuidEmptyAlbumIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), "not-a-guid", trackId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAlbumRouteIdIsMissing_ShouldForwardGuidEmptyAlbumIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), null, trackId.ToString(), libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, Guid.Empty, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTrackRouteIdIsNotParseable_ShouldForwardGuidEmptyTrackIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), "not-a-guid", libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTrackRouteIdIsMissing_ShouldForwardGuidEmptyTrackIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), null, libraryId.ToString());
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(libraryId, artistId, albumId, Guid.Empty),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsNotParseable_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), "not-a-guid");
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryQueryIdIsMissing_ShouldForwardGuidEmptyLibraryIdToApi()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), null);
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
BuildExpectedEndpoint(Guid.Empty, artistId, albumId, trackId),
Arg.Any<Web.Common.Requests.Common.EmptyRequest>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
ConfigureRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId.ToString());
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
_mockApiHttpClient.PostAsync<Web.Common.Requests.Common.EmptyRequest, Web.Common.Requests.Common.EmptyRequest>(
Arg.Any<string>(), Arg.Any<Web.Common.Requests.Common.EmptyRequest>(), Arg.Any<CancellationToken>())
.Returns(Task.FromCanceled<Web.Common.Requests.Common.EmptyRequest>(cancellationTokenSource.Token));
// Act & Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token));
}
/// <summary>
/// Sets the route and query values the endpoint reads the track identity from.
/// </summary>
/// <param name="artistId">The raw route value of the artist Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="albumId">The raw route value of the album Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="trackId">The raw route value of the track Id, or <see langword="null"/> to leave the route value missing.</param>
/// <param name="libraryId">The raw query value of the library Id, or <see langword="null"/> to leave the query string missing.</param>
private void ConfigureRequest(string? artistId, string? albumId, string? trackId, string? libraryId)
{
if (artistId is not null)
_sut.HttpContext.Request.RouteValues["artistId"] = artistId;
if (albumId is not null)
_sut.HttpContext.Request.RouteValues["albumId"] = albumId;
if (trackId is not null)
_sut.HttpContext.Request.RouteValues["trackId"] = trackId;
if (libraryId is not null)
_sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={libraryId}");
}
/// <summary>
/// Builds the upstream endpoint the track restoration is expected to be sent to.
/// </summary>
/// <param name="libraryId">The normalized Id of the media library.</param>
/// <param name="artistId">The normalized Id of the artist.</param>
/// <param name="albumId">The normalized Id of the album.</param>
/// <param name="trackId">The normalized Id of the track.</param>
/// <returns>The expected upstream endpoint.</returns>
private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
{
return ApiRoutes.Music.RESTORE_TRACK
.Replace("{libraryId}", libraryId.ToString())
.Replace("{artistId}", artistId.ToString())
.Replace("{albumId}", albumId.ToString())
.Replace("{trackId}", trackId.ToString());
}
}