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

@@ -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;
}
}