Extends the music library listings with covers, sorting and alpha filtering.

This commit is contained in:
BinaryAlley committed 2026-10-13 13:26:14 +03:00
1 parent 0019821e87
commit 9d82f283e4
69 files changed
+3613 -268

No files matched your search

@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -15,6 +16,9 @@ namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.Music
[ExcludeFromCodeCoverage]
public class AlbumLiteRowFixture
{
private const int MINIMUM_RELEASE_YEAR = 1900;
private const int MAXIMUM_RELEASE_YEAR = 2026;
private readonly Faker _faker = new();
/// <summary>
@@ -23,17 +27,32 @@ public class AlbumLiteRowFixture
/// <param name="id">Optional. The Id of the album.</param>
/// <param name="title">Optional. The title of the album.</param>
/// <param name="totalTracks">Optional. The number of tracks of the release.</param>
/// <param name="coverPath">Optional. The path of the image representing the album.</param>
/// <param name="releaseYear">Optional. The release year of the album.</param>
/// <param name="releaseTypes">Optional. The set of types of the release.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReleaseYear">Whether the release year should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReleaseTypes">Whether the release types should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="AlbumLiteRow"/>.</returns>
public AlbumLiteRow Create(
Guid? id = null,
string? title = null,
int? totalTracks = null)
int? totalTracks = null,
string? coverPath = null,
int? releaseYear = null,
List<MusicReleaseType>? releaseTypes = null,
bool includeCoverPath = true,
bool includeReleaseYear = true,
bool includeReleaseTypes = true)
{
return new AlbumLiteRow
{
Id = id ?? _faker.Random.Guid(),
Title = title ?? _faker.Music.Genre(),
TotalTracks = totalTracks ?? _faker.Random.Int(1, 30)
TotalTracks = totalTracks ?? _faker.Random.Int(1, 30),
CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null,
ReleaseYear = includeReleaseYear ? (releaseYear ?? _faker.Random.Int(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR)) : null,
ReleaseTypes = includeReleaseTypes ? (releaseTypes ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(index => _faker.PickRandom<MusicReleaseType>())]) : null
};
}
@@ -22,15 +22,20 @@ public class ArtistLiteRowFixture
/// </summary>
/// <param name="id">Optional. The Id of the artist.</param>
/// <param name="name">Optional. The name of the artist.</param>
/// <param name="coverPath">Optional. The path of the image representing the artist.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="ArtistLiteRow"/>.</returns>
public ArtistLiteRow Create(
Guid? id = null,
string? name = null)
string? name = null,
string? coverPath = null,
bool includeCoverPath = true)
{
return new ArtistLiteRow
{
Id = id ?? _faker.Random.Guid(),
Name = name ?? _faker.Name.FullName()
Name = name ?? _faker.Name.FullName(),
CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null
};
}
@@ -25,20 +25,23 @@ public class TrackLiteRowFixture
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
/// <param name="includeDiscNumber">Whether the disc number should be included, or forced to <see langword="null"/>.</param>
/// <param name="durationInSeconds">Optional. The duration of the track in seconds.</param>
/// <returns>The created <see cref="TrackLiteRow"/>.</returns>
public TrackLiteRow Create(
Guid? id = null,
string? title = null,
int? trackNumber = null,
int? discNumber = null,
bool includeDiscNumber = true)
bool includeDiscNumber = true,
int? durationInSeconds = null)
{
return new TrackLiteRow
{
Id = id ?? _faker.Random.Guid(),
Title = title ?? _faker.Lorem.Sentence(),
TrackNumber = trackNumber ?? _faker.Random.Int(1, 30),
DiscNumber = includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null
DiscNumber = includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
DurationInSeconds = durationInSeconds ?? _faker.Random.Int(1, 600)
};
}
@@ -3,6 +3,7 @@ using Bogus;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -26,6 +27,10 @@ public class GetArtistsLiteQueryFixture
/// <param name="libraryId">Optional. The Id of the media library whose artists are retrieved, taken from the route.</param>
/// <param name="paginationData">Optional. The pagination data of the query.</param>
/// <param name="searchTerm">Optional. The search term used to filter the artists by name.</param>
/// <param name="filterAlphaKey">Optional. The alpha key used to filter the results by the first character of their name, for the alpha picker.</param>
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Optional. Whether the leading "The " prefix of a name should be ignored when computing the alpha key, or not.</param>
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePaginationData">Whether the pagination data should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSearchTerm">Whether the search term should be included, or forced to <see langword="null"/>.</param>
@@ -34,6 +39,10 @@ public class GetArtistsLiteQueryFixture
string? libraryId = null,
PaginationDataDto? paginationData = null,
string? searchTerm = null,
string? filterAlphaKey = null,
bool shouldIgnoreThePrefixForAlphaPicker = false,
string? sortBy = null,
SortOrder? sortOrder = null,
bool includeLibraryId = true,
bool includePaginationData = true,
bool includeSearchTerm = true)
@@ -41,7 +50,11 @@ public class GetArtistsLiteQueryFixture
return new GetArtistsLiteQuery(
includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null,
includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : null);
includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : null,
filterAlphaKey,
shouldIgnoreThePrefixForAlphaPicker,
sortBy ?? _faker.Lorem.Word(),
sortOrder ?? _faker.PickRandom<SortOrder>());
}
/// <summary>
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Contracts.Fixtures.Core.DTO.Common;
/// <summary>
/// Fixture class for the <see cref="MediaArtworkDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaArtworkDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="MediaArtworkDto"/>.
/// </summary>
/// <param name="type">Optional. The type of the artwork.</param>
/// <param name="ordinal">Optional. The ordinal of the artwork within its type.</param>
/// <param name="path">Optional. The relative path of the stored artwork file.</param>
/// <returns>The created <see cref="MediaArtworkDto"/>.</returns>
public MediaArtworkDto Create(
ArtworkType? type = null,
int? ordinal = null,
string? path = null)
{
return new MediaArtworkDto(
type ?? _faker.PickRandom<ArtworkType>(),
ordinal ?? _faker.Random.Int(0, 5),
path ?? _faker.System.FilePath());
}
/// <summary>
/// Creates a list of <see cref="MediaArtworkDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<MediaArtworkDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -22,22 +23,40 @@ public class GetArtistsLiteRequestFixture
/// <param name="currentPage">Optional. The page of results to retrieve.</param>
/// <param name="perPage">Optional. The maximum number of artists to retrieve per page.</param>
/// <param name="searchTerm">Optional. The search term used to filter the artists by name.</param>
/// <param name="filterAlphaKey">Optional. The alpha key used to filter the results by the first character of their name, for the alpha picker.</param>
/// <param name="shouldIgnoreThePrefixForAlphaPicker">Optional. Whether the leading "The " prefix of a name should be ignored when computing the alpha key, or not.</param>
/// <param name="sortBy">Optional. The name of the field by which to sort the results.</param>
/// <param name="sortOrder">Optional. The direction in which to sort the results.</param>
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePerPage">Whether the per page count should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSearchTerm">Whether the search term should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeFilterAlphaKey">Whether the filter alpha key should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSortBy">Whether the sort field should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeSortOrder">Whether the sort order should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created request to get the lightweight read models of the artists of a media library.</returns>
public GetArtistsLiteRequest Create(
int? currentPage = null,
int? perPage = null,
string? searchTerm = null,
string? filterAlphaKey = null,
bool shouldIgnoreThePrefixForAlphaPicker = false,
string? sortBy = null,
SortOrder? sortOrder = null,
bool includeCurrentPage = true,
bool includePerPage = true,
bool includeSearchTerm = true)
bool includeSearchTerm = true,
bool includeFilterAlphaKey = true,
bool includeSortBy = true,
bool includeSortOrder = true)
{
return new GetArtistsLiteRequest(
includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null,
includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null,
includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : null);
includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : null,
includeFilterAlphaKey ? (filterAlphaKey ?? CreateFilterAlphaKey()) : null,
shouldIgnoreThePrefixForAlphaPicker,
includeSortBy ? (sortBy ?? _faker.Lorem.Word()) : null,
includeSortOrder ? (sortOrder ?? _faker.PickRandom<SortOrder>()) : null);
}
/// <summary>
@@ -49,4 +68,15 @@ public class GetArtistsLiteRequestFixture
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates a random valid alpha key: a single ASCII letter, "#" for names starting with a digit, or "*" for any other first character.
/// </summary>
/// <returns>The created alpha key.</returns>
private string CreateFilterAlphaKey()
{
return _faker.Random.Bool()
? _faker.Random.Char('A', 'Z').ToString()
: _faker.Random.ListItem(new[] { "#", "*" });
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -23,16 +24,35 @@ public class AlbumLiteResponseFixture
/// <param name="id">Optional. The Id of the album.</param>
/// <param name="title">Optional. The title of the album.</param>
/// <param name="totalTracks">Optional. The number of tracks of the release.</param>
/// <param name="coverPath">Optional. The path of the image representing the album.</param>
/// <param name="releaseYear">Optional. The release year of the album.</param>
/// <param name="releaseTypes">Optional. The set of types of the release.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReleaseYear">Whether the release year should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeReleaseTypes">Whether the release types should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="AlbumLiteResponse"/>.</returns>
public AlbumLiteResponse Create(
Guid? id = null,
string? title = null,
int? totalTracks = null)
int? totalTracks = null,
string? coverPath = null,
int? releaseYear = null,
List<MusicReleaseType>? releaseTypes = null,
bool includeCoverPath = true,
bool includeReleaseYear = true,
bool includeReleaseTypes = true)
{
List<MusicReleaseType>? resolvedReleaseTypes = includeReleaseTypes
? (releaseTypes ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _faker.PickRandom<MusicReleaseType>())])
: null;
return new AlbumLiteResponse(
id ?? Guid.NewGuid(),
title ?? _faker.Commerce.ProductName(),
totalTracks ?? _faker.Random.Int(1, 30));
totalTracks ?? _faker.Random.Int(1, 30),
includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null,
includeReleaseYear ? (releaseYear ?? _faker.Random.Int(1900, 2026)) : null,
resolvedReleaseTypes);
}
/// <summary>
@@ -1,8 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
@@ -29,6 +31,7 @@ public class AlbumResponseFixture
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
private readonly TrackResponseFixture _trackResponseFixture = new();
private readonly MediaArtworkDtoFixture _mediaArtworkDtoFixture = new();
/// <summary>
/// Creates a random valid <see cref="AlbumResponse"/>.
@@ -51,6 +54,8 @@ public class AlbumResponseFixture
/// <param name="contributors">Optional. The list of contributor references of the album.</param>
/// <param name="ratings">Optional. The list of ratings of the album.</param>
/// <param name="tracks">Optional. The list of tracks of the album.</param>
/// <param name="coverPath">Optional. The path of the image representing the album.</param>
/// <param name="artwork">Optional. The stored artwork of the album, in display order.</param>
/// <param name="includeMediaFormat">Whether the media format should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePackaging">Whether the packaging should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBarcode">Whether the barcode should be included, or forced to <see langword="null"/>.</param>
@@ -64,6 +69,8 @@ public class AlbumResponseFixture
/// <param name="includeContributors">Whether the contributors should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTracks">Whether the tracks should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtwork">Whether the artwork should be included, or forced to an empty collection.</param>
/// <returns>The created <see cref="AlbumResponse"/>.</returns>
public AlbumResponse Create(
Guid? id = null,
@@ -84,6 +91,8 @@ public class AlbumResponseFixture
List<MediaContributorReferenceDto>? contributors = null,
List<AudioRatingDto>? ratings = null,
List<TrackResponse>? tracks = null,
string? coverPath = null,
List<MediaArtworkDto>? artwork = null,
bool includeMediaFormat = true,
bool includePackaging = true,
bool includeBarcode = true,
@@ -96,8 +105,14 @@ public class AlbumResponseFixture
bool includeUpdatedOnUtc = true,
bool includeContributors = true,
bool includeRatings = true,
bool includeTracks = true)
bool includeTracks = true,
bool includeCoverPath = true,
bool includeArtwork = true)
{
IReadOnlyList<MediaArtworkDto> resolvedArtwork = includeArtwork
? (artwork ?? _mediaArtworkDtoFixture.CreateMany(1))
: [];
return new AlbumResponse(
id ?? Guid.NewGuid(),
artistId ?? Guid.NewGuid(),
@@ -116,7 +131,9 @@ public class AlbumResponseFixture
includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent().ToUniversalTime()) : null,
includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1)) : null,
includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(1)) : null,
includeTracks ? (tracks ?? _trackResponseFixture.CreateMany(1)) : null);
includeTracks ? (tracks ?? _trackResponseFixture.CreateMany(1)) : null,
includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null,
resolvedArtwork);
}
/// <summary>
@@ -22,14 +22,19 @@ public class ArtistLiteResponseFixture
/// </summary>
/// <param name="id">Optional. The Id of the artist.</param>
/// <param name="name">Optional. The name of the artist.</param>
/// <param name="coverPath">Optional. The path of the image representing the artist.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="ArtistLiteResponse"/>.</returns>
public ArtistLiteResponse Create(
Guid? id = null,
string? name = null)
string? name = null,
string? coverPath = null,
bool includeCoverPath = true)
{
return new ArtistLiteResponse(
id ?? Guid.NewGuid(),
name ?? _faker.Name.FullName());
name ?? _faker.Name.FullName(),
includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null);
}
/// <summary>
@@ -44,6 +44,7 @@ public class ArtistResponseFixture
/// <param name="albums">Optional. The list of albums of the artist.</param>
/// <param name="createdOnUtc">Optional. The date and time when the artist was created.</param>
/// <param name="updatedOnUtc">Optional. The date and time when the artist was updated.</param>
/// <param name="coverPath">Optional. The path of the image representing the artist.</param>
/// <param name="includeWebsite">Whether the website should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeMusicBrainzArtistId">Whether the MusicBrainz artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeIpis">Whether the IPI codes should be included, or forced to <see langword="null"/>.</param>
@@ -52,6 +53,7 @@ public class ArtistResponseFixture
/// <param name="includeContributors">Whether the contributors should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeRatings">Whether the ratings should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbums">Whether the albums should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="ArtistResponse"/>.</returns>
public ArtistResponse Create(
Guid? id = null,
@@ -66,6 +68,7 @@ public class ArtistResponseFixture
List<AlbumResponse>? albums = null,
DateTime? createdOnUtc = null,
DateTime? updatedOnUtc = null,
string? coverPath = null,
bool includeWebsite = true,
bool includeMusicBrainzArtistId = true,
bool includeIpis = true,
@@ -73,7 +76,8 @@ public class ArtistResponseFixture
bool includeUpdatedOnUtc = true,
bool includeContributors = true,
bool includeRatings = true,
bool includeAlbums = true)
bool includeAlbums = true,
bool includeCoverPath = true)
{
return new ArtistResponse(
id ?? Guid.NewGuid(),
@@ -87,7 +91,8 @@ public class ArtistResponseFixture
includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent().ToUniversalTime()) : null,
includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1)) : null,
includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(1)) : null,
includeAlbums ? (albums ?? _albumResponseFixture.CreateMany(1)) : null);
includeAlbums ? (albums ?? _albumResponseFixture.CreateMany(1)) : null,
includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null);
}
/// <summary>
@@ -25,19 +25,22 @@ public class TrackLiteResponseFixture
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
/// <param name="includeDiscNumber">Whether the disc number should be included, or forced to <see langword="null"/>.</param>
/// <param name="durationInSeconds">Optional. The duration of the track in seconds.</param>
/// <returns>The created <see cref="TrackLiteResponse"/>.</returns>
public TrackLiteResponse Create(
Guid? id = null,
string? title = null,
int? trackNumber = null,
int? discNumber = null,
bool includeDiscNumber = true)
bool includeDiscNumber = true,
int? durationInSeconds = null)
{
return new TrackLiteResponse(
id ?? _faker.Random.Guid(),
title ?? _faker.Lorem.Sentence(),
trackNumber ?? _faker.Random.Int(1, 30),
includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null);
includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
durationInSeconds ?? _faker.Random.Int(1, 600));
}
/// <summary>
@@ -15,6 +15,7 @@ using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
@@ -44,6 +45,7 @@ public class AlbumRepositoryTests
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
[Fact]
@@ -601,6 +603,112 @@ public class AlbumRepositoryTests
Assert.Equal(expectedRowCount, result.Value.Data.Count);
}
[Fact]
public async Task GetAlbumsLiteByArtistIdAsync_WhenReReleaseYearIsSet_ShouldProjectItAsReleaseYear()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-releaseyear-{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 = _albumEntityFixture.Create(
artistId: artist.Id, libraryId: libraryId, originalReleaseYear: 1975, reReleaseYear: 2011, includeTracks: false, includeMetadata: false);
context.Albums.Add(album);
await context.SaveChangesAsync();
// Act
Result<PaginatedResultDto<AlbumLiteRow>> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
AlbumLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal(2011, row.ReleaseYear);
}
[Fact]
public async Task GetAlbumsLiteByArtistIdAsync_WhenReReleaseYearIsNull_ShouldFallBackToOriginalReleaseYear()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-originalyear-{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 = _albumEntityFixture.Create(
artistId: artist.Id, libraryId: libraryId, originalReleaseYear: 1975, includeReReleaseYear: false, includeTracks: false, includeMetadata: false);
context.Albums.Add(album);
await context.SaveChangesAsync();
// Act
Result<PaginatedResultDto<AlbumLiteRow>> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
AlbumLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal(1975, row.ReleaseYear);
}
[Fact]
public async Task GetAlbumsLiteByArtistIdAsync_WhenTheReleaseHasTypes_ShouldProjectThem()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-releasetypes-{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 = _albumEntityFixture.Create(
artistId: artist.Id, libraryId: libraryId, releaseType: MusicReleaseType.Single, includeTracks: false, includeMetadata: false);
context.Albums.Add(album);
await context.SaveChangesAsync();
// Act
Result<PaginatedResultDto<AlbumLiteRow>> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
AlbumLiteRow row = Assert.Single(result.Value.Data);
Assert.NotNull(row.ReleaseTypes);
Assert.Equal(MusicReleaseType.Single, Assert.Single(row.ReleaseTypes));
}
[Fact]
public async Task GetAlbumsLiteByArtistIdAsync_WhenCoverArtworkExists_ShouldProjectTheCoverPath()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-cover-{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 = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
context.Albums.Add(album);
context.MusicArtwork.Add(
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id, artworkType: ArtworkType.Cover, fileName: "covers/opera.jpg"));
await context.SaveChangesAsync();
// Act
Result<PaginatedResultDto<AlbumLiteRow>> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
AlbumLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal("covers/opera.jpg", row.CoverPath);
}
/// <summary>
/// Creates an album repository backed by the provided context, wiring the real track repository.
/// </summary>
@@ -17,6 +17,7 @@ using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
@@ -51,6 +52,7 @@ public class ArtistRepositoryTests
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
[Fact]
public async Task InsertAsync_WhenCalledWithAValidArtist_ShouldPersistTheArtistAndItsAggregate()
@@ -1079,6 +1081,257 @@ public class ArtistRepositoryTests
Assert.Equal(keptTrackContributor.Id, Assert.Single(storedTrack.Contributors).Id);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldDeleteOnlyTheLibraryArtistsAndTheirChildren()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-deletebylibrary-{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 targetArtist = await SeedArtistAsync(context, libraryId, "Queen");
AlbumEntity targetAlbum = await SeedAlbumAsync(context, libraryId, targetArtist.Id);
context.Tracks.Add(_trackEntityFixture.Create(albumId: targetAlbum.Id, libraryId: libraryId, includeMetadata: false));
ArtistEntity artistOfAnotherLibrary = await SeedArtistAsync(context, Guid.NewGuid(), "Pink Floyd");
await context.SaveChangesAsync();
// Act
Result<Deleted> result = await sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
context.ChangeTracker.Clear();
// Only the artists of the target library are deleted, and the database cascade removes their albums and tracks.
ArtistEntity survivor = Assert.Single(await context.Artists.AsNoTracking().ToListAsync());
Assert.Equal(artistOfAnotherLibrary.Id, survivor.Id);
Assert.Empty(await context.Albums.AsNoTracking().Where(candidate => candidate.LibraryId == libraryId).ToListAsync());
Assert.Empty(await context.Tracks.AsNoTracking().Where(candidate => candidate.LibraryId == libraryId).ToListAsync());
}
[Fact]
public async Task GetAllLiteAsync_WhenAlphaKeyIsTheNumberKey_ShouldMatchOnlyNamesStartingWithADigit()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-lite-alpha-number-{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 numericArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "1984", includeAlbums: false, includeContributors: false);
ArtistEntity letterArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false);
ArtistEntity symbolArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "!Voyager", includeAlbums: false, includeContributors: false);
context.Artists.AddRange(numericArtist, letterArtist, symbolArtist);
await context.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, filterAlphaKey: LibraryItemAlphaKeys.NUMBER);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal("1984", row.Name);
}
[Fact]
public async Task GetAllLiteAsync_WhenAlphaKeyIsTheSymbolKey_ShouldMatchOnlyNamesStartingWithASymbol()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-lite-alpha-symbol-{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 symbolArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "!Voyager", includeAlbums: false, includeContributors: false);
ArtistEntity numericArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "1984", includeAlbums: false, includeContributors: false);
ArtistEntity letterArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false);
context.Artists.AddRange(symbolArtist, numericArtist, letterArtist);
await context.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, filterAlphaKey: LibraryItemAlphaKeys.SYMBOL);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal("!Voyager", row.Name);
}
[Fact]
public async Task GetAllLiteAsync_WhenAlphaKeyIsALetter_ShouldMatchOnlyNamesStartingWithIt()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-lite-alpha-letter-{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 alphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false);
ArtistEntity bravoArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Bravo", includeAlbums: false, includeContributors: false);
ArtistEntity charlieArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Charlie", includeAlbums: false, includeContributors: false);
context.Artists.AddRange(alphaArtist, bravoArtist, charlieArtist);
await context.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, filterAlphaKey: "b");
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal("Bravo", row.Name);
}
[Fact]
public async Task GetAllLiteAsync_WhenSearchTermAndAlphaKeyAreProvided_ShouldCombineThemWithAnd()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-lite-search-alpha-{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 matchingArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha Band", includeAlbums: false, includeContributors: false);
ArtistEntity artistMatchingOnlyTheAlphaKey = _artistEntityFixture.Create(libraryId: libraryId, name: "Adele", includeAlbums: false, includeContributors: false);
ArtistEntity artistMatchingOnlyTheSearchTerm = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta Band", includeAlbums: false, includeContributors: false);
context.Artists.AddRange(matchingArtist, artistMatchingOnlyTheAlphaKey, artistMatchingOnlyTheSearchTerm);
await context.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Band", filterAlphaKey: "a");
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal(matchingArtist.Id, row.Id);
}
[Fact]
public async Task GetAllLiteAsync_WhenIgnoringThePrefix_ShouldFilterOnTheStrippedName()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-lite-alpha-the-{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 beatlesArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "The Beatles", includeAlbums: false, includeContributors: false);
ArtistEntity adeleArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Adele", includeAlbums: false, includeContributors: false);
context.Artists.AddRange(beatlesArtist, adeleArtist);
await context.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, filterAlphaKey: "b", shouldIgnoreThePrefixForAlphaPicker: true);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal("The Beatles", row.Name);
}
[Fact]
public async Task GetAllLiteAsync_WhenNotIgnoringThePrefix_ShouldFilterOnTheFullName()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-lite-alpha-the-off-{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 beatlesArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "The Beatles", includeAlbums: false, includeContributors: false);
ArtistEntity adeleArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Adele", includeAlbums: false, includeContributors: false);
context.Artists.AddRange(beatlesArtist, adeleArtist);
await context.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, filterAlphaKey: "b", shouldIgnoreThePrefixForAlphaPicker: false);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value.Data);
}
[Fact]
public async Task GetAllLiteAsync_WhenIgnoringThePrefixForSorting_ShouldSortByTheStrippedName()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-lite-sort-the-{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 beneathArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beneath the Surface", includeAlbums: false, includeContributors: false);
ArtistEntity beatlesArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "The Beatles", includeAlbums: false, includeContributors: false);
context.Artists.AddRange(beneathArtist, beatlesArtist);
await context.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: true);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
// With the prefix stripped, the sort key of "The Beatles" is "beatles", which sorts before "beneath".
Assert.Equal(["The Beatles", "Beneath the Surface"], result.Value.Data.Select(row => row.Name));
}
[Fact]
public async Task GetAllLiteAsync_WhenCoverArtworkExists_ShouldReturnItsPath()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-lite-cover-{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, name: "Queen", includeAlbums: false, includeContributors: false);
context.Artists.Add(artist);
context.MusicArtwork.Add(
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artist.Id, artworkType: ArtworkType.Cover, fileName: "covers/queen.jpg"));
await context.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal("covers/queen.jpg", row.CoverPath);
}
/// <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>
@@ -0,0 +1,235 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications;
using Lumina.DataAccess.Core.UoW;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MusicLibrary.Specifications;
/// <summary>
/// Contains integration tests for the <see cref="ArtistAlphaFilterSpecification"/> class, exercising it against a real SQLite database.
/// </summary>
[ExcludeFromCodeCoverage]
public class ArtistAlphaFilterSpecificationTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly LuminaDbContext _context;
private readonly ArtistEntityFixture _artistEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ArtistAlphaFilterSpecificationTests"/> class.
/// </summary>
public ArtistAlphaFilterSpecificationTests()
{
// The specification translates to the SQLite glob() function, so it can only be exercised against a real SQLite database.
_connection = new SqliteConnection("Data Source=:memory:");
_connection.Open();
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(_connection).Options);
_context.Database.EnsureCreated();
}
[Fact]
public void ToExpression_WhenAlphaKeyIsNull_ShouldMatchEveryArtist()
{
// Arrange
List<ArtistEntity> artists = SeedArtists("Alpha", "Beta", "1984");
ArtistAlphaFilterSpecification specification = new(null, false);
// Act
List<ArtistEntity> result = [.. _context.Artists.Where(specification.ToExpression())];
// Assert
Assert.Equal(artists.Count, result.Count);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsALowercaseLetter_ShouldMatchOnlyArtistsWhoseNameStartsWithIt()
{
// Arrange
SeedArtists("Foo Fighters", "Helloween", "The Beatles");
ArtistAlphaFilterSpecification specification = new("f", false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal(["Foo Fighters"], result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsAnUppercaseLetter_ShouldMatchArtistsWhoseNameStartsWithItsLowercase()
{
// Arrange
SeedArtists("Foo Fighters", "Helloween");
ArtistAlphaFilterSpecification specification = new("F", false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal(["Foo Fighters"], result);
}
[Fact]
public void ToExpression_WhenNoNameStartsWithTheAlphaKey_ShouldNotMatchAnyArtist()
{
// Arrange
SeedArtists("Foo Fighters", "Helloween");
ArtistAlphaFilterSpecification specification = new("z", false);
// Act
List<ArtistEntity> result = [.. _context.Artists.Where(specification.ToExpression())];
// Assert
Assert.Empty(result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheNumberKey_ShouldMatchOnlyArtistsWhoseNameStartsWithADigit()
{
// Arrange
SeedArtists("1984", "Alpha", "Beta");
ArtistAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal(["1984"], result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheSymbolKey_ShouldMatchOnlyArtistsWhoseNameStartsWithASymbol()
{
// Arrange
SeedArtists("!Important", "1984", "Alpha");
ArtistAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal(["!Important"], result);
}
[Fact]
public void ToExpression_WhenIgnoringThePrefixAndNameStartsWithThe_ShouldMatchOnTheStrippedName()
{
// Arrange
SeedArtists("The Beatles", "Adele");
ArtistAlphaFilterSpecification specification = new("b", true);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal(["The Beatles"], result);
}
[Fact]
public void ToExpression_WhenNotIgnoringThePrefixAndNameStartsWithThe_ShouldNotMatchOnTheStrippedName()
{
// Arrange
SeedArtists("The Beatles", "Adele");
ArtistAlphaFilterSpecification specification = new("b", false);
// Act
List<ArtistEntity> result = [.. _context.Artists.Where(specification.ToExpression())];
// Assert
Assert.Empty(result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheNumberKeyAndNameStartsWithASymbol_ShouldNotMatchIt()
{
// Arrange
SeedArtists("!Voyager", "1984", "Alpha");
ArtistAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
// Only the artist whose name starts with a digit matches; a symbol and a letter do not.
Assert.Equal(["1984"], result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsTheSymbolKeyAndNameIsEmpty_ShouldMatchIt()
{
// Arrange
SeedArtists(string.Empty);
ArtistAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false);
// Act
List<ArtistEntity> result = [.. _context.Artists.Where(specification.ToExpression())];
// Assert
// An empty effective name is neither a letter nor a digit, so it is categorized as a symbol.
Assert.Single(result);
}
[Fact]
public void ToExpression_WhenAlphaKeyIsALetterAndNameIsEmpty_ShouldNotMatchAnyArtist()
{
// Arrange
SeedArtists(string.Empty);
ArtistAlphaFilterSpecification specification = new("a", false);
// Act
List<ArtistEntity> result = [.. _context.Artists.Where(specification.ToExpression())];
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData("a", "Alpha")] // the first letter of the alphabet
[InlineData("b", "Bravo")] // a letter in the middle of the alphabet
[InlineData("c", "Charlie")] // another letter in the middle of the alphabet
public void ToExpression_WhenAlphaKeyIsALetter_ShouldMatchOnlyTheNamesStartingWithIt(string alphaKey, string matchingName)
{
// Arrange
SeedArtists("Alpha", "Bravo", "Charlie");
ArtistAlphaFilterSpecification specification = new(alphaKey, false);
// Act
List<string> result = [.. _context.Artists.Where(specification.ToExpression()).Select(artist => artist.Name)];
// Assert
Assert.Equal([matchingName], result);
}
/// <summary>
/// Seeds artists with the provided names.
/// </summary>
/// <param name="names">The names of the artists to seed.</param>
/// <returns>The seeded <see cref="ArtistEntity"/> instances.</returns>
private List<ArtistEntity> SeedArtists(params string[] names)
{
List<ArtistEntity> entities = [];
foreach (string name in names)
entities.Add(_artistEntityFixture.Create(name: name, includeAlbums: false, includeContributors: false));
_context.Artists.AddRange(entities);
_context.SaveChanges();
return entities;
}
/// <summary>
/// Disposes the database context and its underlying connection.
/// </summary>
public void Dispose()
{
_context.Dispose();
_connection.Dispose();
}
}
@@ -567,7 +567,7 @@ public class TrackRepositoryTests
List<TrackEntity> albumTracks = [firstDiscFirstTrack, firstDiscSecondTrack, secondDiscTrack];
Guid[] expectedOrder = [.. albumTracks
.OrderBy(track => track.DiscNumber)
.OrderBy(track => track.DiscNumber ?? 1)
.ThenBy(track => track.TrackNumber)
.ThenBy(track => track.Id)
.Select(track => track.Id)];
@@ -634,6 +634,34 @@ public class TrackRepositoryTests
Assert.Equal(3, page.PerPage);
Assert.Equal(1, page.NumberOfPages);
Assert.DoesNotContain(page.Data, row => row.Id == trackOfAnotherAlbum.Id);
Assert.Equal(tracks.Select(track => track.DurationInSeconds), page.Data.Select(row => row.DurationInSeconds));
}
[Fact]
public async Task GetTracksLiteByAlbumIdAsync_WhenATrackHasNoDiscNumber_ShouldTreatItAsTheFirstDisc()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-lite-nodisc-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity secondTrackWithoutDiscNumber = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/second.flac", trackNumber: 2, includeMetadata: false);
secondTrackWithoutDiscNumber.DiscNumber = null;
TrackEntity thirdTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/third.flac", trackNumber: 3, includeMetadata: false);
thirdTrack.DiscNumber = 1;
context.Tracks.AddRange(secondTrackWithoutDiscNumber, thirdTrack);
await context.SaveChangesAsync();
// Act
Result<PaginatedResultDto<TrackLiteRow>> result = await sut.GetTracksLiteByAlbumIdAsync(album.Id, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([secondTrackWithoutDiscNumber.Id, thirdTrack.Id], result.Value.Data.Select(row => row.Id));
}
[Theory]
@@ -686,6 +714,60 @@ public class TrackRepositoryTests
Assert.Equal(expectedRowCount, page.Data.Count);
}
[Fact]
public async Task GetByAlbumIdAsync_WhenATrackHasNoDiscNumber_ShouldTreatItAsTheFirstDisc()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-nodisc-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity secondDiscTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/second-disc.flac", trackNumber: 1, includeMetadata: false);
secondDiscTrack.DiscNumber = 2;
TrackEntity trackWithoutDiscNumber = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/first-disc.flac", trackNumber: 2, includeMetadata: false);
trackWithoutDiscNumber.DiscNumber = null;
context.Tracks.AddRange(secondDiscTrack, trackWithoutDiscNumber);
await context.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await sut.GetByAlbumIdAsync(album.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
// A track without a disc number belongs to the first disc, so it is ordered before the tracks of disc 2.
Assert.Equal([trackWithoutDiscNumber.Id, secondDiscTrack.Id], result.Value.Select(track => track.Id));
}
[Fact]
public async Task GetTracksLiteByAlbumIdAsync_WhenCalled_ShouldProjectTheDurationInSeconds()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-lite-duration-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
TrackRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
AlbumEntity album = await SeedAlbumAsync(context, libraryId);
TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/the-prophet-song.flac", includeMetadata: false);
track.DurationInSeconds = 367;
context.Tracks.Add(track);
await context.SaveChangesAsync();
// Act
Result<PaginatedResultDto<TrackLiteRow>> result = await sut.GetTracksLiteByAlbumIdAsync(album.Id, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
TrackLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal(367, row.DurationInSeconds);
}
/// <summary>
/// Seeds an artist and the album that owns the tracks of the library identified by <paramref name="libraryId"/>, so that the required foreign keys of a track are satisfied.
/// </summary>
@@ -77,6 +77,7 @@ public class GetAlbumTracksLiteEndpointTests : IClassFixture<AuthenticatedLumina
Assert.Equal(1, tracks!.Count);
TrackLiteResponse track = Assert.Single(tracks.Data);
Assert.Equal("Bohemian Rhapsody", track.Title);
Assert.True(track.DurationInSeconds > 0);
}
[Fact]
@@ -18,6 +18,7 @@ using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
@@ -33,7 +34,8 @@ public class GetArtistAlbumsLiteEndpointTests : IClassFixture<AuthenticatedLumin
private readonly AuthenticatedLuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
@@ -79,6 +81,8 @@ public class GetArtistAlbumsLiteEndpointTests : IClassFixture<AuthenticatedLumin
Assert.Equal(2, albums.Data.Count);
Assert.Contains(albums.Data, album => album.Title == "A Night at the Opera");
Assert.Contains(albums.Data, album => album.Title == "News of the World");
// The release types and the release year are exposed by the read model, so the lite listing can group and order the releases of an artist.
Assert.All(albums.Data, album => Assert.NotEmpty(album.ReleaseTypes!));
}
[Fact]
@@ -97,6 +97,155 @@ public class GetArtistsLiteEndpointTests : IClassFixture<AuthenticatedLuminaApiF
Assert.Equal(0, paginatedArtists.Count);
}
[Fact]
public async Task GetArtistsLite_WhenCalledWithFilterAlphaKeyLetter_ShouldReturnOnlyArtistsStartingWithThatLetter()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
await SeedArtistAsync(libraryId, "Queen");
await SeedArtistAsync(libraryId, "The Queen");
await SeedArtistAsync(libraryId, "Radiohead");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?filterAlphaKey=q");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedArtists);
ArtistLiteResponse artist = Assert.Single(paginatedArtists!.Data);
Assert.Equal("Queen", artist.Name);
Assert.Equal(1, paginatedArtists.Count);
}
[Fact]
public async Task GetArtistsLite_WhenCalledWithFilterAlphaKeyLetterAndIgnoreThePrefix_ShouldIncludeThePrefixedNames()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
await SeedArtistAsync(libraryId, "Queen");
await SeedArtistAsync(libraryId, "The Queen");
await SeedArtistAsync(libraryId, "Radiohead");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?filterAlphaKey=q&shouldIgnoreThePrefixForAlphaPicker=true");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedArtists);
Assert.Equal(2, paginatedArtists!.Count);
Assert.Contains(paginatedArtists.Data, artist => artist.Name == "Queen");
Assert.Contains(paginatedArtists.Data, artist => artist.Name == "The Queen");
}
[Fact]
public async Task GetArtistsLite_WhenCalledWithFilterAlphaKeyNumber_ShouldReturnOnlyArtistsStartingWithADigit()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
await SeedArtistAsync(libraryId, "1984");
await SeedArtistAsync(libraryId, "7th Sense");
await SeedArtistAsync(libraryId, "Adele");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?filterAlphaKey=%23");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedArtists);
Assert.Equal(2, paginatedArtists!.Count);
Assert.Contains(paginatedArtists.Data, artist => artist.Name == "1984");
Assert.Contains(paginatedArtists.Data, artist => artist.Name == "7th Sense");
}
[Fact]
public async Task GetArtistsLite_WhenCalledWithFilterAlphaKeySymbol_ShouldReturnOnlyArtistsStartingWithASymbol()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
await SeedArtistAsync(libraryId, "!Important");
await SeedArtistAsync(libraryId, "1984");
await SeedArtistAsync(libraryId, "Adele");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?filterAlphaKey=%2A");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedArtists);
ArtistLiteResponse artist = Assert.Single(paginatedArtists!.Data);
Assert.Equal("!Important", artist.Name);
Assert.Equal(1, paginatedArtists.Count);
}
[Fact]
public async Task GetArtistsLite_WhenCalledWithSearchTermAndFilterAlphaKey_ShouldReturnOnlyArtistsSatisfyingBothFilters()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
// The search term matches only one artist, while the alpha key matches only the other, so no artist satisfies both filters at once.
await SeedArtistAsync(libraryId, "The Fellowship Band");
await SeedArtistAsync(libraryId, "Zoo");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?searchTerm={Uri.EscapeDataString("Fellowship")}&filterAlphaKey=z");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedArtists);
Assert.Empty(paginatedArtists!.Data);
Assert.Equal(0, paginatedArtists.Count);
}
[Fact]
public async Task GetArtistsLite_WhenSortedByNameAscending_ShouldReturnArtistsInAscendingOrder()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
await SeedArtistAsync(libraryId, "Zulu");
await SeedArtistAsync(libraryId, "Mike");
await SeedArtistAsync(libraryId, "Alpha");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?sortBy=name&sortOrder=Ascending");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedArtists);
Assert.Equal(new[] { "Alpha", "Mike", "Zulu" }, paginatedArtists!.Data.Select(artist => artist.Name));
}
[Fact]
public async Task GetArtistsLite_WhenSortedByNameDescending_ShouldReturnArtistsInDescendingOrder()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId);
await SeedArtistAsync(libraryId, "Zulu");
await SeedArtistAsync(libraryId, "Mike");
await SeedArtistAsync(libraryId, "Alpha");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?sortBy=name&sortOrder=Descending");
// Assert
response.EnsureSuccessStatusCode();
PaginatedResponse<ArtistLiteResponse>? paginatedArtists = await response.Content.ReadFromJsonAsync<PaginatedResponse<ArtistLiteResponse>>(_jsonOptions);
Assert.NotNull(paginatedArtists);
Assert.Equal(new[] { "Zulu", "Mike", "Alpha" }, paginatedArtists!.Data.Select(artist => artist.Name));
}
[Fact]
public async Task GetArtistsLite_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
{
@@ -261,6 +261,8 @@ public class AlbumEntityMappingTests
Assert.Equal(entity.Id, result.Id);
Assert.Equal(entity.ArtistId, result.ArtistId);
Assert.Equal(entity.LibraryId, result.LibraryId);
// No cover path is supplied by default, so the response exposes none.
Assert.Null(result.CoverPath);
Assert.Equal(entity.Title, result.Metadata.Title);
Assert.Equal(entity.OriginalTitle, result.Metadata.OriginalTitle);
Assert.Equal(entity.Description, result.Metadata.Description);
@@ -346,4 +348,19 @@ public class AlbumEntityMappingTests
Assert.Equal(entities[i].Title, results[i].Metadata.Title);
}
}
[Fact]
public void ToResponse_WhenCoverPathIsProvided_ShouldMapIt()
{
// Arrange
AlbumEntity entity = _albumEntityFixture.Create();
string coverPath = "/media/albums/cover.jpg";
// Act
AlbumResponse result = entity.ToResponse(coverPath);
// Assert
Assert.NotNull(result);
Assert.Equal(coverPath, result.CoverPath);
}
}
@@ -36,6 +36,9 @@ public class AlbumLiteRowMappingTests
Assert.Equal(readModel.Id, result.Id);
Assert.Equal(readModel.Title, result.Title);
Assert.Equal(readModel.TotalTracks, result.TotalTracks);
Assert.Equal(readModel.CoverPath, result.CoverPath);
Assert.Equal(readModel.ReleaseYear, result.ReleaseYear);
Assert.Equal(readModel.ReleaseTypes, result.ReleaseTypes);
}
[Fact]
@@ -53,6 +56,9 @@ public class AlbumLiteRowMappingTests
Assert.Equal(readModels.Select(readModel => readModel.Id), results.Select(response => response.Id));
Assert.Equal(readModels.Select(readModel => readModel.Title), results.Select(response => response.Title));
Assert.Equal(readModels.Select(readModel => readModel.TotalTracks), results.Select(response => response.TotalTracks));
Assert.Equal(readModels.Select(readModel => readModel.CoverPath), results.Select(response => response.CoverPath));
Assert.Equal(readModels.Select(readModel => readModel.ReleaseYear), results.Select(response => response.ReleaseYear));
Assert.Equal(readModels.Select(readModel => readModel.ReleaseTypes), results.Select(response => response.ReleaseTypes));
}
[Fact]
@@ -113,6 +113,8 @@ public class ArtistEntityMappingTests
Assert.NotNull(result);
Assert.Equal(entity.Id, result.Id);
Assert.Equal(entity.LibraryId, result.LibraryId);
// No cover path is supplied by default, so the response exposes none.
Assert.Null(result.CoverPath);
Assert.Equal(entity.Name, result.Metadata.Name);
Assert.Equal(entity.Website, result.Website);
Assert.Equal(entity.MusicBrainzArtistId, result.MusicBrainzArtistId);
@@ -186,4 +188,19 @@ public class ArtistEntityMappingTests
Assert.Equal(paginatedEntities.Count, result.Count);
Assert.Equal(paginatedEntities.NumberOfPages, result.NumberOfPages);
}
[Fact]
public void ToResponse_WhenCoverPathIsProvided_ShouldMapIt()
{
// Arrange
ArtistEntity entity = _artistEntityFixture.Create();
string coverPath = "/media/artists/cover.jpg";
// Act
ArtistResponse result = entity.ToResponse(coverPath);
// Assert
Assert.NotNull(result);
Assert.Equal(coverPath, result.CoverPath);
}
}
@@ -35,6 +35,7 @@ public class ArtistLiteRowMappingTests
Assert.NotNull(result);
Assert.Equal(readModel.Id, result.Id);
Assert.Equal(readModel.Name, result.Name);
Assert.Equal(readModel.CoverPath, result.CoverPath);
}
[Fact]
@@ -51,6 +52,7 @@ public class ArtistLiteRowMappingTests
Assert.Equal(readModels.Count, results.Count);
Assert.Equal(readModels.Select(readModel => readModel.Id), results.Select(response => response.Id));
Assert.Equal(readModels.Select(readModel => readModel.Name), results.Select(response => response.Name));
Assert.Equal(readModels.Select(readModel => readModel.CoverPath), results.Select(response => response.CoverPath));
}
[Fact]
@@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.A
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -99,4 +100,24 @@ public class GetArtistsLiteRequestMappingTests
Assert.Equal(2, result.PaginationData.CurrentPage);
Assert.Equal(25, result.PaginationData.PerPage);
}
[Fact]
public void ToQuery_WhenAlphaAndSortingAreProvided_ShouldMapThem()
{
// Arrange
GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(
filterAlphaKey: "q",
shouldIgnoreThePrefixForAlphaPicker: true,
sortBy: "name",
sortOrder: SortOrder.Descending);
// Act
GetArtistsLiteQuery result = request.ToQuery("library-route");
// Assert
Assert.Equal("q", result.FilterAlphaKey);
Assert.True(result.ShouldIgnoreThePrefixForAlphaPicker);
Assert.Equal("name", result.SortBy);
Assert.Equal(SortOrder.Descending, result.SortOrder);
}
}
@@ -37,6 +37,7 @@ public class TrackLiteRowMappingTests
Assert.Equal(readModel.Title, result.Title);
Assert.Equal(readModel.TrackNumber, result.TrackNumber);
Assert.Equal(readModel.DiscNumber, result.DiscNumber);
Assert.Equal(readModel.DurationInSeconds, result.DurationInSeconds);
}
[Fact]
@@ -12,8 +12,11 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Al
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
@@ -30,12 +33,14 @@ public class GetAlbumQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetAlbumQuery> _mockValidator;
private readonly GetAlbumQueryHandler _sut;
private readonly Guid _userId;
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly GetAlbumQueryFixture _getAlbumQueryFixture = new();
/// <summary>
@@ -44,18 +49,22 @@ public class GetAlbumQueryHandlerTests
public GetAlbumQueryHandlerTests()
{
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetAlbumQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes.
// Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes, and the album has no stored artwork.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetAlbumQuery>()).Returns([]);
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
_sut = new GetAlbumQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
@@ -70,6 +79,13 @@ public class GetAlbumQueryHandlerTests
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: true, includeMetadata: true);
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
List<MusicArtworkEntity> artwork = [
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "/media/cover.jpg"),
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Back, ordinal: 0, fileName: "/media/back.jpg"),
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Booklet, ordinal: 0, includeFileName: false)
];
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>(artwork));
GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
// Act
@@ -83,6 +99,13 @@ public class GetAlbumQueryHandlerTests
Assert.Equal(album.Title, result.Value.Metadata.Title);
Assert.NotNull(result.Value.Tracks);
Assert.Equal(album.Tracks.Count, result.Value.Tracks!.Count);
// The cover is exposed on its own, and every stored piece of artwork is exposed in order, while the ones whose file is not stored yet are left out.
Assert.Equal("/media/cover.jpg", result.Value.CoverPath);
Assert.Equal(2, result.Value.Artwork.Count);
Assert.Equal(ArtworkType.Cover, result.Value.Artwork[0].Type);
Assert.Equal("/media/cover.jpg", result.Value.Artwork[0].Path);
Assert.Equal(ArtworkType.Back, result.Value.Artwork[1].Type);
Assert.Equal("/media/back.jpg", result.Value.Artwork[1].Path);
await _mockAlbumRepository.Received(1).GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
@@ -220,4 +243,112 @@ public class GetAlbumQueryHandlerTests
await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkRepositoryFails_ShouldReturnFailureResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenAlbumHasNoArtwork_ShouldReturnNullCoverPathAndEmptyArtwork()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
// Act
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value.CoverPath);
Assert.Empty(result.Value.Artwork);
}
[Fact]
public async Task HandleAsync_WhenMultipleArtworkExist_ShouldMapEveryStoredArtworkAndExcludeUnstoredOnes()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
List<MusicArtworkEntity> artwork = [
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "/media/cover.jpg"),
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Booklet, ordinal: 1, includeFileName: false),
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Booklet, ordinal: 2, fileName: string.Empty),
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Booklet, ordinal: 3, fileName: " "),
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Back, ordinal: 0, fileName: "/media/back.jpg")
];
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>(artwork));
// Act
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
// Artwork whose file has not been stored yet (null, empty or whitespace) is left out, and the stored ones keep their order, type and ordinal.
Assert.Equal(2, result.Value.Artwork.Count);
Assert.Equal(ArtworkType.Cover, result.Value.Artwork[0].Type);
Assert.Equal(0, result.Value.Artwork[0].Ordinal);
Assert.Equal("/media/cover.jpg", result.Value.Artwork[0].Path);
Assert.Equal(ArtworkType.Back, result.Value.Artwork[1].Type);
Assert.Equal(0, result.Value.Artwork[1].Ordinal);
Assert.Equal("/media/back.jpg", result.Value.Artwork[1].Path);
await _mockMusicArtworkRepository.Received(1).GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenMultipleCoversExist_ShouldUseTheFirstCoverFileName()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId);
GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString());
_mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(album));
List<MusicArtworkEntity> artwork = [
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "/media/front.jpg"),
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Cover, ordinal: 1, fileName: "/media/alternate.jpg")
];
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>(artwork));
// Act
Result<AlbumResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("/media/front.jpg", result.Value.CoverPath);
}
}
@@ -12,8 +12,11 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Ar
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
@@ -30,12 +33,14 @@ public class GetArtistQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetArtistQuery> _mockValidator;
private readonly GetArtistQueryHandler _sut;
private readonly Guid _userId;
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly GetArtistQueryFixture _getArtistQueryFixture = new();
/// <summary>
@@ -44,18 +49,22 @@ public class GetArtistQueryHandlerTests
public GetArtistQueryHandlerTests()
{
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetArtistQuery>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes.
// Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes, and the artist has no stored artwork.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<GetArtistQuery>()).Returns([]);
_mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
_sut = new GetArtistQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
}
@@ -199,4 +208,97 @@ public class GetArtistQueryHandlerTests
await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenArtworkRepositoryFails_ShouldReturnFailureResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId);
GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString());
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenArtistHasNoArtwork_ShouldReturnNullCoverPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId);
GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString());
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>([]));
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value.CoverPath);
}
[Fact]
public async Task HandleAsync_WhenArtistHasCoverArtwork_ShouldMapCoverPathAndRequestArtistArtwork()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId);
GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString());
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
List<MusicArtworkEntity> artwork = [
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "/media/artist.jpg")
];
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>(artwork));
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("/media/artist.jpg", result.Value.CoverPath);
await _mockMusicArtworkRepository.Received(1).GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheCoverHasNoStoredFileName_ShouldReturnNullCoverPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId);
GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString());
_mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(artist));
// A cover whose file has not been stored yet yields no cover path, even when another piece of artwork is already stored.
List<MusicArtworkEntity> artwork = [
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, artworkType: ArtworkType.Cover, ordinal: 0, includeFileName: false),
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, artworkType: ArtworkType.Back, ordinal: 0, fileName: "/media/back.jpg")
];
_mockMusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicArtworkEntity>>(artwork));
// Act
Result<ArtistResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value.CoverPath);
}
}
@@ -247,4 +247,41 @@ public class GetArtistsLiteQueryHandlerTests
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.DidNotReceive().GetAllLiteAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenQueryHasAlphaFilterAndSorting_ShouldPassThemToTheRepository()
{
// Arrange
Guid libraryId = Guid.NewGuid();
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(
libraryId: libraryId.ToString(),
searchTerm: "Queen",
filterAlphaKey: "Q",
shouldIgnoreThePrefixForAlphaPicker: true,
sortBy: "name",
sortOrder: SortOrder.Descending);
PaginatedResultDto<ArtistLiteRow> paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0);
_mockArtistRepository.GetAllLiteAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Any<string?>(),
Arg.Any<SortOrder?>(),
Arg.Any<LibraryFilterDto>(),
cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(paginatedArtists));
// Act
await _sut.HandleAsync(query, CancellationToken.None);
// Assert
await _mockArtistRepository.Received(1).GetAllLiteAsync(
Arg.Any<PaginationDataDto?>(),
Arg.Is<string?>(sortBy => sortBy == "name"),
Arg.Is<SortOrder?>(sortOrder => sortOrder == SortOrder.Descending),
Arg.Is<LibraryFilterDto>(filter =>
filter.LibraryId == libraryId &&
filter.SearchTerm == "Queen" &&
filter.FilterAlphaKey == "Q" &&
filter.ShouldIgnoreThePrefixForAlphaPicker),
cancellationToken: Arg.Any<CancellationToken>());
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite;
using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite;
using Lumina.Application.UnitTests.Common.Setup;
@@ -63,4 +64,155 @@ public class GetArtistsLiteQueryValidatorTests
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Theory]
[InlineData("AB")] // more than one character
[InlineData("1")] // a digit, which is not a letter, the number bucket, or the symbol bucket
public void Validate_WhenFilterAlphaKeyIsNotASingleLetterOrSpecialKey_ShouldHaveValidationError(string filterAlphaKey)
{
// Arrange
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(filterAlphaKey: filterAlphaKey);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.InvalidFilterAlphaKey);
}
[Theory]
[InlineData("Q")] // a single letter
[InlineData("q")] // a single lower case letter
[InlineData("#")] // the number bucket
[InlineData("*")] // the symbol bucket
public void Validate_WhenFilterAlphaKeyIsASingleLetterOrSpecialKey_ShouldNotHaveValidationError(string filterAlphaKey)
{
// Arrange
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(filterAlphaKey: filterAlphaKey);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_WhenFilterAlphaKeyIsNull_ShouldNotHaveValidationError()
{
// Arrange
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(filterAlphaKey: null);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Theory]
[InlineData(LibraryItemAlphaKeys.NUMBER)] // the number bucket constant
[InlineData(LibraryItemAlphaKeys.SYMBOL)] // the symbol bucket constant
public void Validate_WhenFilterAlphaKeyIsTheSpecialConstant_ShouldNotHaveValidationError(string filterAlphaKey)
{
// Arrange
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(filterAlphaKey: filterAlphaKey);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Theory]
[InlineData("A")] // upper case A
[InlineData("B")] // upper case B
[InlineData("C")] // upper case C
[InlineData("D")] // upper case D
[InlineData("E")] // upper case E
[InlineData("F")] // upper case F
[InlineData("G")] // upper case G
[InlineData("H")] // upper case H
[InlineData("I")] // upper case I
[InlineData("J")] // upper case J
[InlineData("K")] // upper case K
[InlineData("L")] // upper case L
[InlineData("M")] // upper case M
[InlineData("N")] // upper case N
[InlineData("O")] // upper case O
[InlineData("P")] // upper case P
[InlineData("Q")] // upper case Q
[InlineData("R")] // upper case R
[InlineData("S")] // upper case S
[InlineData("T")] // upper case T
[InlineData("U")] // upper case U
[InlineData("V")] // upper case V
[InlineData("W")] // upper case W
[InlineData("X")] // upper case X
[InlineData("Y")] // upper case Y
[InlineData("Z")] // upper case Z
[InlineData("a")] // lower case a
[InlineData("b")] // lower case b
[InlineData("c")] // lower case c
[InlineData("d")] // lower case d
[InlineData("e")] // lower case e
[InlineData("f")] // lower case f
[InlineData("g")] // lower case g
[InlineData("h")] // lower case h
[InlineData("i")] // lower case i
[InlineData("j")] // lower case j
[InlineData("k")] // lower case k
[InlineData("l")] // lower case l
[InlineData("m")] // lower case m
[InlineData("n")] // lower case n
[InlineData("o")] // lower case o
[InlineData("p")] // lower case p
[InlineData("q")] // lower case q
[InlineData("r")] // lower case r
[InlineData("s")] // lower case s
[InlineData("t")] // lower case t
[InlineData("u")] // lower case u
[InlineData("v")] // lower case v
[InlineData("w")] // lower case w
[InlineData("x")] // lower case x
[InlineData("y")] // lower case y
[InlineData("z")] // lower case z
public void Validate_WhenFilterAlphaKeyIsAnySingleAsciiLetter_ShouldNotHaveValidationError(string filterAlphaKey)
{
// Arrange
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(filterAlphaKey: filterAlphaKey);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Theory]
[InlineData("")] // empty string, which is not a single letter or a special key
[InlineData("AB")] // two letters
[InlineData("ABC")] // several letters
[InlineData("1")] // a digit, which is not a letter, a number bucket or a symbol bucket
[InlineData("9")] // another digit
[InlineData("_")] // an underscore, which is not an ASCII letter
[InlineData("é")] // a non-ASCII letter
[InlineData("#!")] // the number bucket followed by another character
[InlineData("**")] // two symbol buckets, which is not the exact symbol constant
[InlineData("#A")] // the number bucket followed by a letter
[InlineData("*A")] // the symbol bucket followed by a letter
[InlineData(" A")] // a leading space followed by a letter
[InlineData("A ")] // a letter followed by a trailing space
public void Validate_WhenFilterAlphaKeyIsNotAValidAlphaKey_ShouldHaveValidationError(string filterAlphaKey)
{
// Arrange
GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(filterAlphaKey: filterAlphaKey);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.InvalidFilterAlphaKey);
}
}
@@ -47,6 +47,7 @@ public class AlbumRepositoryTests
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
/// <summary>
@@ -741,6 +742,112 @@ public class AlbumRepositoryTests
Assert.Equal(12, row.TotalTracks);
}
[Fact]
public async Task GetAlbumsLiteByArtistIdAsync_WhenReReleaseYearIsSet_ShouldProjectItAsReleaseYear()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId, originalReleaseYear: 1975, reReleaseYear: 2011, includeTracks: false, includeMetadata: false);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
// Act
Result<PaginatedResultDto<AlbumLiteRow>> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
AlbumLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal(2011, row.ReleaseYear);
}
[Fact]
public async Task GetAlbumsLiteByArtistIdAsync_WhenReReleaseYearIsNull_ShouldFallBackToOriginalReleaseYear()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId, originalReleaseYear: 1975, includeReReleaseYear: false, includeTracks: false, includeMetadata: false);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
// Act
Result<PaginatedResultDto<AlbumLiteRow>> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
AlbumLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal(1975, row.ReleaseYear);
}
[Fact]
public async Task GetAlbumsLiteByArtistIdAsync_WhenTheReleaseHasTypes_ShouldProjectThem()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId, releaseType: MusicReleaseType.Single, includeTracks: false, includeMetadata: false);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
// Act
Result<PaginatedResultDto<AlbumLiteRow>> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
AlbumLiteRow row = Assert.Single(result.Value.Data);
Assert.NotNull(row.ReleaseTypes);
Assert.Equal(MusicReleaseType.Single, Assert.Single(row.ReleaseTypes));
}
[Fact]
public async Task GetAlbumsLiteByArtistIdAsync_WhenCoverArtworkExists_ShouldProjectTheCoverPath()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false);
_mockContext.Albums.Add(album);
_mockContext.MusicArtwork.Add(
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id, artworkType: ArtworkType.Cover, fileName: "covers/opera.jpg"));
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
// Act
Result<PaginatedResultDto<AlbumLiteRow>> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
AlbumLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal("covers/opera.jpg", row.CoverPath);
}
[Fact]
public async Task GetAlbumsLiteByArtistIdAsync_WhenNoCoverArtworkExists_ShouldProjectNullCoverPath()
{
// Arrange
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false);
_mockContext.Albums.Add(album);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
// Act
Result<PaginatedResultDto<AlbumLiteRow>> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
AlbumLiteRow row = Assert.Single(result.Value.Data);
Assert.Null(row.CoverPath);
}
[Fact]
public async Task GetAlbumsNeedingMetadataCountAsync_WhenAlbumsHaveMixedMetadataStatuses_ShouldCountOnlyTheNotEnrichedOnesOfTheLibrary()
{
@@ -53,6 +53,7 @@ public class ArtistRepositoryTests
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new();
private readonly BaseFilterDtoFixture _baseFilterDtoFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ArtistRepositoryTests"/> class.
@@ -1041,6 +1042,28 @@ public class ArtistRepositoryTests
Assert.Equal([betaArtist.Id, alphaArtist.Id], result.Value.Data.Select(artist => artist.Id));
}
[Fact]
public async Task GetAllLiteAsync_WhenIgnoringTheNamePrefixForSorting_ShouldSortByNameStrippedOfItsPrefix()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity beneathArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beneath the Surface", includeAlbums: false, includeContributors: false);
ArtistEntity beatlesArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "The Beatles", includeAlbums: false, includeContributors: false);
_mockContext.Artists.AddRange(beneathArtist, beatlesArtist);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: true);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
// Without stripping the prefix, "The Beatles" would be sorted after "Beneath the Surface", since its sort key would start with "the" instead of "beatles".
Assert.Equal(["The Beatles", "Beneath the Surface"], result.Value.Data.Select(row => row.Name));
}
[Fact]
public async Task GetAllLiteAsync_WhenCalled_ShouldProjectOnlyTheIdAndTheName()
{
@@ -1202,6 +1225,92 @@ public class ArtistRepositoryTests
Assert.Equal(1, result.Value);
}
[Fact]
public async Task GetAllLiteAsync_WhenCoverArtworkExists_ShouldReturnItsPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
_mockContext.Artists.Add(artist);
_mockContext.MusicArtwork.Add(
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artist.Id, artworkType: ArtworkType.Cover, fileName: "covers/queen.jpg"));
await _mockContext.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal("covers/queen.jpg", row.CoverPath);
}
[Fact]
public async Task GetAllLiteAsync_WhenOnlyNonCoverArtworkExists_ShouldReturnNullCoverPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
_mockContext.Artists.Add(artist);
_mockContext.MusicArtwork.Add(
_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artist.Id, artworkType: ArtworkType.Front, fileName: "front/queen.jpg"));
await _mockContext.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistLiteRow row = Assert.Single(result.Value.Data);
Assert.Null(row.CoverPath);
}
[Fact]
public async Task GetAllLiteAsync_WhenNoCoverArtworkExists_ShouldReturnNullCoverPath()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
_mockContext.Artists.Add(artist);
await _mockContext.SaveChangesAsync();
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
ArtistLiteRow row = Assert.Single(result.Value.Data);
Assert.Null(row.CoverPath);
}
[Fact]
public async Task GetAllLiteAsync_WhenNotIgnoringTheNamePrefixForSorting_ShouldKeepThePrefix()
{
// Arrange
Guid libraryId = Guid.NewGuid();
ArtistEntity beneathArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beneath the Surface", includeAlbums: false, includeContributors: false);
ArtistEntity beatlesArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "The Beatles", includeAlbums: false, includeContributors: false);
_mockContext.Artists.AddRange(beneathArtist, beatlesArtist);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: false);
// Act
Result<PaginatedResultDto<ArtistLiteRow>> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
// The prefix is not stripped, so the sort key of "The Beatles" starts with "the" and it sorts after "Beneath the Surface".
Assert.Equal(["Beneath the Surface", "The Beatles"], result.Value.Data.Select(row => row.Name));
}
/// <summary>
/// Marks the provided artist, its albums and its tracks as enriched.
/// </summary>
@@ -637,7 +637,7 @@ public class TrackRepositoryTests
List<TrackEntity> albumTracks = [firstDiscFirstTrack, firstDiscFirstTieTrack, firstDiscSecondTrack, secondDiscTrack];
Guid[] expectedOrder = [.. albumTracks
.OrderBy(track => track.DiscNumber)
.OrderBy(track => track.DiscNumber ?? 1)
.ThenBy(track => track.TrackNumber)
.ThenBy(track => track.Id)
.Select(track => track.Id)];
@@ -651,6 +651,27 @@ public class TrackRepositoryTests
Assert.DoesNotContain(result.Value, track => track.Id == trackOfAnotherAlbum.Id);
}
[Fact]
public async Task GetByAlbumIdAsync_WhenATrackHasNoDiscNumber_ShouldTreatItAsTheFirstDisc()
{
// Arrange
Guid albumId = Guid.NewGuid();
TrackEntity secondDiscTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/second-disc.flac", trackNumber: 1, includeMetadata: false);
secondDiscTrack.DiscNumber = 2;
TrackEntity firstDiscTrackWithoutDiscNumber = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/first-disc.flac", trackNumber: 2, includeMetadata: false);
firstDiscTrackWithoutDiscNumber.DiscNumber = null;
_mockContext.Tracks.AddRange(secondDiscTrack, firstDiscTrackWithoutDiscNumber);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<TrackEntity>> result = await _sut.GetByAlbumIdAsync(albumId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
// A track without a disc number belongs to the first disc, so it is ordered before the tracks of disc 2.
Assert.Equal([firstDiscTrackWithoutDiscNumber.Id, secondDiscTrack.Id], result.Value.Select(track => track.Id));
}
[Fact]
public async Task GetByAlbumIdAsync_WhenCalled_ShouldIncludeTheRelatedCollections()
{
@@ -707,6 +728,26 @@ public class TrackRepositoryTests
Assert.Equal([firstTrack.Id, secondTrack.Id], page.Data.Select(row => row.Id));
}
[Fact]
public async Task GetTracksLiteByAlbumIdAsync_WhenATrackHasNoDiscNumber_ShouldTreatItAsTheFirstDisc()
{
// Arrange
Guid albumId = Guid.NewGuid();
TrackEntity thirdTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/third.flac", trackNumber: 3, includeMetadata: false);
thirdTrack.DiscNumber = 1;
TrackEntity secondTrackWithoutDiscNumber = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/second.flac", trackNumber: 2, includeMetadata: false);
secondTrackWithoutDiscNumber.DiscNumber = null;
_mockContext.Tracks.AddRange(thirdTrack, secondTrackWithoutDiscNumber);
await _mockContext.SaveChangesAsync();
// Act
Result<PaginatedResultDto<TrackLiteRow>> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal([secondTrackWithoutDiscNumber.Id, thirdTrack.Id], result.Value.Data.Select(row => row.Id));
}
[Theory]
[InlineData(1, 2, 1, 2)] // The first page is fully returned.
[InlineData(2, 2, 2, 2)] // A middle page is fully returned.
@@ -792,6 +833,28 @@ public class TrackRepositoryTests
Assert.Equal("Killer Queen", row.Title);
Assert.Equal(9, row.TrackNumber);
Assert.Equal(3, row.DiscNumber);
Assert.Equal(track.DurationInSeconds, row.DurationInSeconds);
}
[Fact]
public async Task GetTracksLiteByAlbumIdAsync_WhenCalled_ShouldProjectTheDurationInSeconds()
{
// Arrange
Guid albumId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/the-prophet-song.flac", includeMetadata: false);
track.DurationInSeconds = 367;
_mockContext.Tracks.Add(track);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
// Act
Result<PaginatedResultDto<TrackLiteRow>> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, paginationData, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
TrackLiteRow row = Assert.Single(result.Value.Data);
Assert.Equal(367, row.DurationInSeconds);
}
[Fact]