diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowFixture.cs
new file mode 100644
index 00000000..1e717757
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowFixture.cs
@@ -0,0 +1,49 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class AlbumLiteRowFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the album.
+ /// Optional. The title of the album.
+ /// Optional. The number of tracks of the release.
+ /// The created .
+ public AlbumLiteRow Create(
+ Guid? id = null,
+ string? title = null,
+ int? totalTracks = null)
+ {
+ return new AlbumLiteRow
+ {
+ Id = id ?? _faker.Random.Guid(),
+ Title = title ?? _faker.Music.Genre(),
+ TotalTracks = totalTracks ?? _faker.Random.Int(1, 30)
+ };
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs
index 3a2c86fb..e7c7b23b 100644
--- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs
@@ -20,7 +20,6 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Au
[ExcludeFromCodeCoverage]
public class AlbumEntityFixture
{
- private readonly Random _random = new();
private readonly Faker _faker = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly TagEntityFixture _tagEntityFixture = new();
@@ -36,18 +35,46 @@ public class AlbumEntityFixture
/// Optional. The Id of the media library that owns the album.
/// Optional. The title of the album.
/// Optional. The tracks of the album.
- /// Whether the album should own a generated track, or no track at all.
- /// Whether the owned metadata collections (Tags, Genres, Contributors, Ratings) should be included, or forced to empty collections.
/// Optional. The original release date of the album.
/// Optional. The original release year of the album.
/// Optional. The re-release date of the album.
/// Optional. The re-release year of the album.
/// Optional. The barcode of the album.
+ /// Optional. The original title of the album.
+ /// Optional. A brief description or summary of the album.
+ /// Optional. The language code of the album.
+ /// Optional. The language name of the album.
+ /// Optional. The language native name of the album.
+ /// Optional. The original language code of the album.
+ /// Optional. The original language name of the album.
+ /// Optional. The original language native name of the album.
+ /// Optional. The release type of the album.
+ /// Optional. The release status of the album.
+ /// Optional. The total number of discs of the album.
+ /// Optional. The media format of the album.
+ /// Optional. The catalog number of the album.
+ /// Optional. The MusicBrainz release identifier of the album.
+ /// Optional. The MusicBrainz release group identifier of the album.
+ /// Optional. The MusicBrainz release artist identifier of the album.
+ /// Whether the album should own a generated track, or no track at all.
+ /// Whether the owned metadata collections (Tags, Genres, Contributors, Ratings) should be included, or forced to empty collections.
/// Whether the original release date should be included, or forced to .
/// Whether the original release year should be included, or forced to .
/// Whether the re-release date should be included, or forced to .
/// Whether the re-release year should be included, or forced to .
/// Whether the barcode should be included, or forced to .
+ /// Whether the original title should be included, or forced to .
+ /// Whether the description should be included, or forced to .
+ /// Whether the language of the album should be included, or forced to .
+ /// Whether the original language of the album should be included, or forced to .
+ /// Whether the release type should be included, or forced to .
+ /// Whether the release status should be included, or forced to .
+ /// Whether the total number of discs should be included, or forced to .
+ /// Whether the media format should be included, or forced to .
+ /// Whether the catalog number should be included, or forced to .
+ /// Whether the MusicBrainz release identifier should be included, or forced to .
+ /// Whether the MusicBrainz release group identifier should be included, or forced to .
+ /// Whether the MusicBrainz release artist identifier should be included, or forced to .
/// The created .
public AlbumEntity Create(
Guid? id = null,
@@ -55,26 +82,54 @@ public class AlbumEntityFixture
Guid? libraryId = null,
string? title = null,
List? tracks = null,
- bool includeTracks = true,
- bool includeMetadata = true,
DateOnly? originalReleaseDate = null,
int? originalReleaseYear = null,
DateOnly? reReleaseDate = null,
int? reReleaseYear = null,
string? barcode = null,
+ string? originalTitle = null,
+ string? description = null,
+ string? languageCode = null,
+ string? languageName = null,
+ string? languageNativeName = null,
+ string? originalLanguageCode = null,
+ string? originalLanguageName = null,
+ string? originalLanguageNativeName = null,
+ MusicReleaseType? releaseType = null,
+ MusicReleaseStatus? releaseStatus = null,
+ int? totalDiscs = null,
+ MusicMediaFormat? mediaFormat = null,
+ string? catalogNumber = null,
+ Guid? musicBrainzReleaseId = null,
+ Guid? musicBrainzReleaseGroupId = null,
+ Guid? musicBrainzReleaseArtistId = null,
+ bool includeTracks = true,
+ bool includeMetadata = true,
bool includeOriginalReleaseDate = true,
bool includeOriginalReleaseYear = true,
bool includeReReleaseDate = true,
bool includeReReleaseYear = true,
- bool includeBarcode = true)
+ bool includeBarcode = true,
+ bool includeOriginalTitle = true,
+ bool includeDescription = true,
+ bool includeLanguage = true,
+ bool includeOriginalLanguage = true,
+ bool includeReleaseType = true,
+ bool includeReleaseStatus = true,
+ bool includeTotalDiscs = true,
+ bool includeMediaFormat = true,
+ bool includeCatalogNumber = true,
+ bool includeMusicBrainzReleaseId = true,
+ bool includeMusicBrainzReleaseGroupId = true,
+ bool includeMusicBrainzReleaseArtistId = true)
{
Guid resolvedId = id ?? Guid.NewGuid();
Guid resolvedArtistId = artistId ?? Guid.NewGuid();
Guid resolvedLibraryId = libraryId ?? Guid.NewGuid();
const int MAXIMUM_RELEASE_YEAR = 2026;
- int resolvedOriginalReleaseYear = originalReleaseYear ?? _random.Next(1900, MAXIMUM_RELEASE_YEAR);
+ int resolvedOriginalReleaseYear = originalReleaseYear ?? Random.Shared.Next(1900, MAXIMUM_RELEASE_YEAR);
int resolvedReReleaseYearUpperBound = Math.Max(resolvedOriginalReleaseYear + 1, MAXIMUM_RELEASE_YEAR);
- int resolvedReReleaseYear = reReleaseYear ?? _random.Next(resolvedOriginalReleaseYear, resolvedReReleaseYearUpperBound);
+ int resolvedReReleaseYear = reReleaseYear ?? Random.Shared.Next(resolvedOriginalReleaseYear, resolvedReReleaseYearUpperBound);
DateOnly resolvedOriginalReleaseDate = originalReleaseDate ?? _faker.DateOnlyBetween(new DateOnly(resolvedOriginalReleaseYear, 1, 1), new DateOnly(resolvedOriginalReleaseYear, 12, 31));
DateOnly resolvedReReleaseDate = reReleaseDate ?? _faker.DateOnlyBetween(resolvedReReleaseYear == resolvedOriginalReleaseYear ? resolvedOriginalReleaseDate : new DateOnly(resolvedReReleaseYear, 1, 1), new DateOnly(resolvedReReleaseYear, 12, 31));
List resolvedTracks = tracks ?? (includeTracks ? [_trackEntityFixture.Create(albumId: resolvedId, libraryId: resolvedLibraryId, includeMetadata: includeMetadata, includeOriginalReleaseDate: includeOriginalReleaseDate, includeOriginalReleaseYear: includeOriginalReleaseYear, includeReReleaseDate: includeReReleaseDate, includeReReleaseYear: includeReReleaseYear)] : []);
@@ -91,30 +146,30 @@ public class AlbumEntityFixture
UpdatedBy = null
})
.RuleFor(x => x.Title, f => title ?? f.Random.String2(f.Random.Number(1, 255)))
- .RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255)))
- .RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000)))
+ .RuleFor(x => x.OriginalTitle, f => includeOriginalTitle ? (originalTitle ?? f.Random.String2(f.Random.Number(1, 255))) : null)
+ .RuleFor(x => x.Description, f => includeDescription ? (description ?? f.Random.String2(f.Random.Number(1, 2000))) : null)
.RuleFor(x => x.OriginalReleaseDate, includeOriginalReleaseDate ? resolvedOriginalReleaseDate : (DateOnly?)null)
.RuleFor(x => x.OriginalReleaseYear, includeOriginalReleaseYear ? resolvedOriginalReleaseYear : (int?)null)
.RuleFor(x => x.ReReleaseDate, includeReReleaseDate ? resolvedReReleaseDate : (DateOnly?)null)
.RuleFor(x => x.ReReleaseYear, includeReReleaseYear ? resolvedReReleaseYear : (int?)null)
.RuleFor(x => x.ReleaseCountry, f => f.PickRandom())
.RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50)))
- .RuleFor(x => x.LanguageCode, f => f.Random.String2(2))
- .RuleFor(x => x.LanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
- .RuleFor(x => x.LanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50)))
- .RuleFor(x => x.OriginalLanguageCode, f => f.Random.String2(2))
- .RuleFor(x => x.OriginalLanguageName, f => f.Random.String2(f.Random.Number(1, 50)))
- .RuleFor(x => x.OriginalLanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50)))
- .RuleFor(x => x.ReleaseType, f => f.PickRandom())
- .RuleFor(x => x.ReleaseStatus, f => f.PickRandom())
- .RuleFor(x => x.TotalDiscs, _random.Next(1, 3))
+ .RuleFor(x => x.LanguageCode, f => includeLanguage ? (languageCode ?? f.Random.String2(2)) : null)
+ .RuleFor(x => x.LanguageName, f => includeLanguage ? (languageName ?? f.Random.String2(f.Random.Number(1, 50))) : null)
+ .RuleFor(x => x.LanguageNativeName, f => includeLanguage ? (languageNativeName ?? f.Random.String2(f.Random.Number(1, 50))) : null)
+ .RuleFor(x => x.OriginalLanguageCode, f => includeOriginalLanguage ? (originalLanguageCode ?? f.Random.String2(2)) : null)
+ .RuleFor(x => x.OriginalLanguageName, f => includeOriginalLanguage ? (originalLanguageName ?? f.Random.String2(f.Random.Number(1, 50))) : null)
+ .RuleFor(x => x.OriginalLanguageNativeName, f => includeOriginalLanguage ? (originalLanguageNativeName ?? f.Random.String2(f.Random.Number(1, 50))) : null)
+ .RuleFor(x => x.ReleaseType, f => includeReleaseType ? (releaseType ?? f.PickRandom()) : (MusicReleaseType?)null)
+ .RuleFor(x => x.ReleaseStatus, f => includeReleaseStatus ? (releaseStatus ?? f.PickRandom()) : (MusicReleaseStatus?)null)
+ .RuleFor(x => x.TotalDiscs, includeTotalDiscs ? (totalDiscs ?? Random.Shared.Next(1, 3)) : (int?)null)
.RuleFor(x => x.TotalTracks, resolvedTracks.Count)
- .RuleFor(x => x.MediaFormat, f => f.PickRandom())
+ .RuleFor(x => x.MediaFormat, f => includeMediaFormat ? (mediaFormat ?? f.PickRandom()) : (MusicMediaFormat?)null)
.RuleFor(x => x.Barcode, f => includeBarcode ? (barcode ?? f.Random.String2(f.Random.Number(12, 13), "0123456789")) : null)
- .RuleFor(x => x.CatalogNumber, f => f.Random.String2(f.Random.Number(1, 50)))
- .RuleFor(x => x.MusicBrainzReleaseId, f => f.Random.Guid())
- .RuleFor(x => x.MusicBrainzReleaseGroupId, f => f.Random.Guid())
- .RuleFor(x => x.MusicBrainzReleaseArtistId, f => f.Random.Guid())
+ .RuleFor(x => x.CatalogNumber, f => includeCatalogNumber ? (catalogNumber ?? f.Random.String2(f.Random.Number(1, 50))) : null)
+ .RuleFor(x => x.MusicBrainzReleaseId, f => includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? f.Random.Guid()) : (Guid?)null)
+ .RuleFor(x => x.MusicBrainzReleaseGroupId, f => includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? f.Random.Guid()) : (Guid?)null)
+ .RuleFor(x => x.MusicBrainzReleaseArtistId, f => includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? f.Random.Guid()) : (Guid?)null)
.RuleFor(x => x.Tags, f => includeMetadata ? [.. _tagEntityFixture.CreateMany(f.Random.Number(1, 3))] : [])
.RuleFor(x => x.Genres, f => includeMetadata ? [.. _genreEntityFixture.CreateMany(f.Random.Number(1, 3))] : [])
.RuleFor(x => x.Contributors, f => includeMetadata ? _albumContributorEntityFixture.CreateMany(f.Random.Number(1, 3), albumId: resolvedId) : [])
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandFixture.cs
new file mode 100644
index 00000000..773d80c0
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandFixture.cs
@@ -0,0 +1,130 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
+using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class AddAlbumCommandFixture
+{
+ private readonly Faker _faker = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+ private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
+ private readonly AddTrackCommandFixture _addTrackCommandFixture = new();
+
+ ///
+ /// Creates a random valid command to add an album.
+ ///
+ /// Optional. The Id of the media library the album belongs to, taken from the route.
+ /// Optional. The Id of the artist the album belongs to, taken from the route.
+ /// Optional. The album metadata of the album.
+ /// Optional. The physical or digital medium of the album.
+ /// Optional. The barcode of the album.
+ /// Optional. The catalog number of the album.
+ /// Optional. The MusicBrainz identifier of the release.
+ /// Optional. The MusicBrainz identifier of the release group.
+ /// Optional. The MusicBrainz identifier of the release artist.
+ /// Optional. The media contributors that performed on the album.
+ /// Optional. The ratings of the album.
+ /// Optional. The tracks of the album.
+ /// Optional. The Id of the album, when it already exists.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the metadata should be included, or forced to .
+ /// Whether the media format should be included, or forced to .
+ /// Whether the barcode should be included, or forced to .
+ /// Whether the catalog number should be included, or forced to .
+ /// Whether the MusicBrainz release Id should be included, or forced to .
+ /// Whether the MusicBrainz release group Id should be included, or forced to .
+ /// Whether the MusicBrainz release artist Id should be included, or forced to .
+ /// Whether the contributors should be included, or forced to .
+ /// Whether the ratings should be included, or forced to .
+ /// Whether the tracks should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// The created command to add an album.
+ public AddAlbumCommand Create(
+ string? libraryId = null,
+ string? artistId = null,
+ AlbumMetadataDto? metadata = null,
+ MusicMediaFormat? mediaFormat = null,
+ string? barcode = null,
+ string? catalogNumber = null,
+ Guid? musicBrainzReleaseId = null,
+ Guid? musicBrainzReleaseGroupId = null,
+ Guid? musicBrainzReleaseArtistId = null,
+ List? contributors = null,
+ List? ratings = null,
+ List? tracks = null,
+ Guid? albumId = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeMetadata = true,
+ bool includeMediaFormat = true,
+ bool includeBarcode = true,
+ bool includeCatalogNumber = true,
+ bool includeMusicBrainzReleaseId = true,
+ bool includeMusicBrainzReleaseGroupId = true,
+ bool includeMusicBrainzReleaseArtistId = true,
+ bool includeContributors = true,
+ bool includeRatings = true,
+ bool includeTracks = true,
+ bool includeAlbumId = true)
+ {
+ string? resolvedLibraryId = includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null;
+ string? resolvedArtistId = includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null;
+
+ return new AddAlbumCommand(
+ resolvedLibraryId,
+ resolvedArtistId,
+ includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null,
+ includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null,
+ includeBarcode ? (barcode ?? _faker.Random.String2(_faker.Random.Int(12, 13), "0123456789")) : null,
+ includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(_faker.Random.Int(1, 50))) : null,
+ includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
+ includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
+ includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
+ includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
+ includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
+ includeTracks ? (tracks ?? GenerateTracks(resolvedLibraryId, resolvedArtistId)) : null,
+ includeAlbumId ? (albumId ?? _faker.Random.Guid()) : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+
+ ///
+ /// Generates the tracks of the album, tied to the album's library and artist identifiers.
+ ///
+ /// The Id of the media library the tracks belong to.
+ /// The Id of the artist the tracks belong to.
+ /// The generated tracks.
+ private List GenerateTracks(string? libraryId, string? artistId)
+ {
+ return [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _addTrackCommandFixture.Create(libraryId: libraryId, artistId: artistId))];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandFixture.cs
new file mode 100644
index 00000000..1d740915
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandFixture.cs
@@ -0,0 +1,50 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteAlbumCommandFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the album belongs to, taken from the route.
+ /// Optional. The Id of the artist the album belongs to, taken from the route.
+ /// Optional. The Id of the album to delete, taken from the route.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// The created .
+ public DeleteAlbumCommand Create(
+ string? libraryId = null,
+ string? artistId = null,
+ string? albumId = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeAlbumId = true)
+ {
+ return new DeleteAlbumCommand(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandFixture.cs
new file mode 100644
index 00000000..6f158dbc
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandFixture.cs
@@ -0,0 +1,108 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateAlbumCommandFixture
+{
+ private readonly Faker _faker = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+ private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
+
+ ///
+ /// Creates a random valid command to update an album.
+ ///
+ /// Optional. The Id of the media library the album belongs to, taken from the route.
+ /// Optional. The Id of the artist the album belongs to, taken from the route.
+ /// Optional. The Id of the album to update, taken from the route.
+ /// Optional. The album metadata of the album.
+ /// Optional. The physical or digital medium of the album.
+ /// Optional. The barcode of the album.
+ /// Optional. The catalog number of the album.
+ /// Optional. The MusicBrainz identifier of the release.
+ /// Optional. The MusicBrainz identifier of the release group.
+ /// Optional. The MusicBrainz identifier of the release artist.
+ /// Optional. The media contributors that performed on the album.
+ /// Optional. The ratings of the album.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// Whether the metadata should be included, or forced to .
+ /// Whether the media format should be included, or forced to .
+ /// Whether the barcode should be included, or forced to .
+ /// Whether the catalog number should be included, or forced to .
+ /// Whether the MusicBrainz release Id should be included, or forced to .
+ /// Whether the MusicBrainz release group Id should be included, or forced to .
+ /// Whether the MusicBrainz release artist Id should be included, or forced to .
+ /// Whether the contributors should be included, or forced to .
+ /// Whether the ratings should be included, or forced to .
+ /// The created command to update an album.
+ public UpdateAlbumCommand Create(
+ string? libraryId = null,
+ string? artistId = null,
+ string? albumId = null,
+ AlbumMetadataDto? metadata = null,
+ MusicMediaFormat? mediaFormat = null,
+ string? barcode = null,
+ string? catalogNumber = null,
+ Guid? musicBrainzReleaseId = null,
+ Guid? musicBrainzReleaseGroupId = null,
+ Guid? musicBrainzReleaseArtistId = null,
+ List? contributors = null,
+ List? ratings = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeAlbumId = true,
+ bool includeMetadata = true,
+ bool includeMediaFormat = true,
+ bool includeBarcode = true,
+ bool includeCatalogNumber = true,
+ bool includeMusicBrainzReleaseId = true,
+ bool includeMusicBrainzReleaseGroupId = true,
+ bool includeMusicBrainzReleaseArtistId = true,
+ bool includeContributors = true,
+ bool includeRatings = true)
+ {
+ return new UpdateAlbumCommand(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
+ includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null,
+ includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null,
+ includeBarcode ? (barcode ?? _faker.Random.String2(_faker.Random.Int(12, 13), "0123456789")) : null,
+ includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(_faker.Random.Int(1, 50))) : null,
+ includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
+ includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
+ includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
+ includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
+ includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryFixture.cs
new file mode 100644
index 00000000..ec886392
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryFixture.cs
@@ -0,0 +1,50 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetAlbumQueryFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the album belongs to, taken from the route.
+ /// Optional. The Id of the artist the album belongs to, taken from the route.
+ /// Optional. The Id of the album to get, taken from the route.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// The created .
+ public GetAlbumQuery Create(
+ string? libraryId = null,
+ string? artistId = null,
+ string? albumId = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeAlbumId = true)
+ {
+ return new GetAlbumQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryFixture.cs
new file mode 100644
index 00000000..c6e20583
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryFixture.cs
@@ -0,0 +1,50 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetAlbumTracksQueryFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the album belongs to, taken from the route.
+ /// Optional. The Id of the artist the album belongs to, taken from the route.
+ /// Optional. The Id of the album whose tracks are retrieved, taken from the route.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// The created .
+ public GetAlbumTracksQuery Create(
+ string? libraryId = null,
+ string? artistId = null,
+ string? albumId = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeAlbumId = true)
+ {
+ return new GetAlbumTracksQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryFixture.cs
new file mode 100644
index 00000000..2dfa84ca
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryFixture.cs
@@ -0,0 +1,59 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
+using Lumina.Application.Fixtures.Common.DTO.Pagination;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetAlbumTracksLiteQueryFixture
+{
+ private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the album belongs to, taken from the route.
+ /// Optional. The Id of the artist the album belongs to, taken from the route.
+ /// Optional. The Id of the album whose tracks are retrieved, taken from the route.
+ /// Optional. The pagination data of the query.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// Whether the pagination data should be included, or forced to .
+ /// The created .
+ public GetAlbumTracksLiteQuery Create(
+ string? libraryId = null,
+ string? artistId = null,
+ string? albumId = null,
+ PaginationDataDto? paginationData = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeAlbumId = true,
+ bool includePaginationData = true)
+ {
+ return new GetAlbumTracksLiteQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
+ includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDtoFixture.cs
new file mode 100644
index 00000000..bc52b188
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDtoFixture.cs
@@ -0,0 +1,165 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.Common;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.Common;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class AlbumMetadataDtoFixture
+{
+ private const int MINIMUM_RELEASE_YEAR = 1900;
+ private const int MAXIMUM_RELEASE_YEAR = 2026;
+
+ private readonly Faker _faker = new();
+ private readonly GenreDtoFixture _genreDtoFixture = new();
+ private readonly TagDtoFixture _tagDtoFixture = new();
+ private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
+ private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The title of the album.
+ /// Optional. The original title of the album.
+ /// Optional. A brief description or summary of the album.
+ /// Optional. The release information of the album.
+ /// Optional. The language of the album.
+ /// Optional. The original language of the album.
+ /// Optional. The tags that describe or categorize the album.
+ /// Optional. The genres associated with the album.
+ /// Optional. The type of the release.
+ /// Optional. The status of the release.
+ /// Optional. The number of discs of the release.
+ /// Optional. The number of tracks of the release.
+ /// Whether the title should be included, or forced to .
+ /// Whether the original title should be included, or forced to .
+ /// Whether the description should be included, or forced to .
+ /// Whether the release information should be included, or forced to .
+ /// Whether the language should be included, or forced to .
+ /// Whether the original language should be included, or forced to .
+ /// Whether the tags should be included, or forced to .
+ /// Whether the genres should be included, or forced to .
+ /// Whether the release type should be included, or forced to .
+ /// Whether the release status should be included, or forced to .
+ /// Whether the total number of discs should be included, or forced to .
+ /// Whether the total number of tracks should be included, or forced to .
+ /// The created .
+ public AlbumMetadataDto Create(
+ string? title = null,
+ string? originalTitle = null,
+ string? description = null,
+ ReleaseInfoDto? releaseInfo = null,
+ LanguageInfoDto? language = null,
+ LanguageInfoDto? originalLanguage = null,
+ List? tags = null,
+ List? genres = null,
+ MusicReleaseType? releaseType = null,
+ MusicReleaseStatus? releaseStatus = null,
+ int? totalDiscs = null,
+ int? totalTracks = null,
+ bool includeTitle = true,
+ bool includeOriginalTitle = true,
+ bool includeDescription = true,
+ bool includeReleaseInfo = true,
+ bool includeLanguage = true,
+ bool includeOriginalLanguage = true,
+ bool includeTags = true,
+ bool includeGenres = true,
+ bool includeReleaseType = true,
+ bool includeReleaseStatus = true,
+ bool includeTotalDiscs = true,
+ bool includeTotalTracks = true)
+ {
+ return new AlbumMetadataDto(
+ includeTitle ? (title ?? _faker.Music.Genre()) : null,
+ includeOriginalTitle ? (originalTitle ?? _faker.Music.Genre()) : null,
+ includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null,
+ includeReleaseInfo ? (releaseInfo ?? GenerateReleaseInfo()) : null,
+ includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null,
+ includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null,
+ includeTags ? (tags ?? GenerateDistinctTags()) : null,
+ includeGenres ? (genres ?? GenerateDistinctGenres()) : null,
+ includeReleaseType ? (releaseType ?? _faker.PickRandom()) : null,
+ includeReleaseStatus ? (releaseStatus ?? _faker.PickRandom()) : null,
+ includeTotalDiscs ? (totalDiscs ?? _faker.Random.Int(1, 3)) : null,
+ includeTotalTracks ? (totalTracks ?? _faker.Random.Int(1, 30)) : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+
+ ///
+ /// Creates a random valid with consistent dates and years.
+ ///
+ /// The created .
+ private ReleaseInfoDto GenerateReleaseInfo()
+ {
+ int originalReleaseYear = Random.Shared.Next(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR);
+ int reReleaseYear = Random.Shared.Next(originalReleaseYear, MAXIMUM_RELEASE_YEAR);
+ return _releaseInfoDtoFixture.Create(
+ originalReleaseDate: new DateOnly(originalReleaseYear, 1, 1),
+ originalReleaseYear: originalReleaseYear,
+ reReleaseDate: new DateOnly(reReleaseYear, 1, 1),
+ reReleaseYear: reReleaseYear,
+ releaseCountry: _faker.PickRandom(),
+ releaseVersion: _faker.Random.String2(_faker.Random.Number(1, 50)));
+ }
+
+ ///
+ /// Creates two genres with distinct names, so that the storage deduplication never collapses them into one.
+ ///
+ /// The created genres.
+ private List GenerateDistinctGenres()
+ {
+ return
+ [
+ _genreDtoFixture.Create(name: CreateUniqueName()),
+ _genreDtoFixture.Create(name: CreateUniqueName())
+ ];
+ }
+
+ ///
+ /// Creates two tags with distinct names, so that the storage deduplication never collapses them into one.
+ ///
+ /// The created tags.
+ private List GenerateDistinctTags()
+ {
+ return
+ [
+ _tagDtoFixture.Create(name: CreateUniqueName()),
+ _tagDtoFixture.Create(name: CreateUniqueName())
+ ];
+ }
+
+ ///
+ /// Creates a unique name, so that the generated genres and tags never collapse into one after storage deduplication.
+ ///
+ /// A unique name of at most 50 characters.
+ private string CreateUniqueName()
+ {
+ string uniqueSuffix = Guid.NewGuid().ToString("N")[..12];
+ int maximumWordLength = 50 - uniqueSuffix.Length - 1;
+ string word = _faker.Lorem.Word();
+ string truncatedWord = word.Length > maximumWordLength ? word[..maximumWordLength] : word;
+ return $"{truncatedWord}-{uniqueSuffix}";
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestFixture.cs
new file mode 100644
index 00000000..2c5f4520
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestFixture.cs
@@ -0,0 +1,101 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class AddAlbumRequestFixture
+{
+ private readonly Faker _faker = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly AddTrackRequestFixture _addTrackRequestFixture = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+ private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
+
+ ///
+ /// Creates a random valid request to add an album.
+ ///
+ /// Optional. The album metadata of the album.
+ /// Optional. The physical or digital medium of the album.
+ /// Optional. The barcode of the album.
+ /// Optional. The catalog number of the album.
+ /// Optional. The MusicBrainz identifier of the release.
+ /// Optional. The MusicBrainz identifier of the release group.
+ /// Optional. The MusicBrainz identifier of the release artist.
+ /// Optional. The media contributors that performed on the album.
+ /// Optional. The ratings of the album.
+ /// Optional. The tracks of the album.
+ /// Whether the metadata should be included, or forced to .
+ /// Whether the contributors list should be included, or forced to .
+ /// Whether the ratings list should be included, or forced to .
+ /// Whether the tracks list should be included, or forced to .
+ /// Whether the media format should be included, or forced to .
+ /// Whether the barcode should be included, or forced to .
+ /// Whether the catalog number should be included, or forced to .
+ /// Whether the MusicBrainz release Id should be included, or forced to .
+ /// Whether the MusicBrainz release group Id should be included, or forced to .
+ /// Whether the MusicBrainz release artist Id should be included, or forced to .
+ /// The created request to add an album.
+ public AddAlbumRequest Create(
+ AlbumMetadataDto? metadata = null,
+ MusicMediaFormat? mediaFormat = null,
+ string? barcode = null,
+ string? catalogNumber = null,
+ Guid? musicBrainzReleaseId = null,
+ Guid? musicBrainzReleaseGroupId = null,
+ Guid? musicBrainzReleaseArtistId = null,
+ List? contributors = null,
+ List? ratings = null,
+ List? tracks = null,
+ bool includeMetadata = true,
+ bool includeContributors = true,
+ bool includeRatings = true,
+ bool includeTracks = true,
+ bool includeMediaFormat = true,
+ bool includeBarcode = true,
+ bool includeCatalogNumber = true,
+ bool includeMusicBrainzReleaseId = true,
+ bool includeMusicBrainzReleaseGroupId = true,
+ bool includeMusicBrainzReleaseArtistId = true)
+ {
+ return new AddAlbumRequest(
+ includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null,
+ includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null,
+ includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null,
+ includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(10)) : null,
+ includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
+ includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
+ includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
+ includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null,
+ includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null,
+ includeTracks ? (tracks ?? _addTrackRequestFixture.CreateMany(_faker.Random.Int(1, 3))) : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestFixture.cs
new file mode 100644
index 00000000..cbf07c50
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestFixture.cs
@@ -0,0 +1,93 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateAlbumRequestFixture
+{
+ private readonly Faker _faker = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+ private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
+
+ ///
+ /// Creates a random valid request to update an album.
+ ///
+ /// Optional. The album metadata of the album.
+ /// Optional. The physical or digital medium of the album.
+ /// Optional. The barcode of the album.
+ /// Optional. The catalog number of the album.
+ /// Optional. The MusicBrainz identifier of the release.
+ /// Optional. The MusicBrainz identifier of the release group.
+ /// Optional. The MusicBrainz identifier of the release artist.
+ /// Optional. The media contributors that performed on the album.
+ /// Optional. The ratings of the album.
+ /// Whether the metadata should be included, or forced to .
+ /// Whether the contributors list should be included, or forced to .
+ /// Whether the ratings list should be included, or forced to .
+ /// Whether the media format should be included, or forced to .
+ /// Whether the barcode should be included, or forced to .
+ /// Whether the catalog number should be included, or forced to .
+ /// Whether the MusicBrainz release Id should be included, or forced to .
+ /// Whether the MusicBrainz release group Id should be included, or forced to .
+ /// Whether the MusicBrainz release artist Id should be included, or forced to .
+ /// The created request to update an album.
+ public UpdateAlbumRequest Create(
+ AlbumMetadataDto? metadata = null,
+ MusicMediaFormat? mediaFormat = null,
+ string? barcode = null,
+ string? catalogNumber = null,
+ Guid? musicBrainzReleaseId = null,
+ Guid? musicBrainzReleaseGroupId = null,
+ Guid? musicBrainzReleaseArtistId = null,
+ List? contributors = null,
+ List? ratings = null,
+ bool includeMetadata = true,
+ bool includeContributors = true,
+ bool includeRatings = true,
+ bool includeMediaFormat = true,
+ bool includeBarcode = true,
+ bool includeCatalogNumber = true,
+ bool includeMusicBrainzReleaseId = true,
+ bool includeMusicBrainzReleaseGroupId = true,
+ bool includeMusicBrainzReleaseArtistId = true)
+ {
+ return new UpdateAlbumRequest(
+ includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null,
+ includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null,
+ includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null,
+ includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(10)) : null,
+ includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null,
+ includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null,
+ includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null,
+ includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null,
+ includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteResponseFixture.cs
new file mode 100644
index 00000000..5fc48178
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteResponseFixture.cs
@@ -0,0 +1,47 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class AlbumLiteResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the album.
+ /// Optional. The title of the album.
+ /// Optional. The number of tracks of the release.
+ /// The created .
+ public AlbumLiteResponse Create(
+ Guid? id = null,
+ string? title = null,
+ int? totalTracks = null)
+ {
+ return new AlbumLiteResponse(
+ id ?? Guid.NewGuid(),
+ title ?? _faker.Commerce.ProductName(),
+ totalTracks ?? _faker.Random.Int(1, 30));
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponseFixture.cs
new file mode 100644
index 00000000..22ea8889
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponseFixture.cs
@@ -0,0 +1,116 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class AlbumResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+ private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
+ private readonly TrackResponseFixture _trackResponseFixture = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the album.
+ /// Optional. The Id of the artist the album belongs to.
+ /// Optional. The Id of the media library the album belongs to.
+ /// Optional. The album metadata of the album.
+ /// Optional. The physical or digital medium of the album.
+ /// Optional. The barcode of the album.
+ /// Optional. The catalog number of the album.
+ /// Optional. The MusicBrainz identifier of the release.
+ /// Optional. The MusicBrainz identifier of the release group.
+ /// Optional. The MusicBrainz identifier of the release artist.
+ /// Optional. The date and time when the album was created.
+ /// Optional. The date and time when the album was updated.
+ /// Optional. The list of contributor references of the album.
+ /// Optional. The list of ratings of the album.
+ /// Optional. The list of tracks of the album.
+ /// Whether the media format should be included, or forced to .
+ /// Whether the barcode should be included, or forced to .
+ /// Whether the catalog number should be included, or forced to .
+ /// Whether the MusicBrainz release Id should be included, or forced to .
+ /// Whether the MusicBrainz release group Id should be included, or forced to .
+ /// Whether the MusicBrainz release artist Id should be included, or forced to .
+ /// Whether the update date should be included, or forced to .
+ /// Whether the contributors should be included, or forced to .
+ /// Whether the ratings should be included, or forced to .
+ /// Whether the tracks should be included, or forced to .
+ /// The created .
+ public AlbumResponse Create(
+ Guid? id = null,
+ Guid? artistId = null,
+ Guid? libraryId = null,
+ AlbumMetadataDto? metadata = null,
+ MusicMediaFormat? mediaFormat = null,
+ string? barcode = null,
+ string? catalogNumber = null,
+ Guid? musicBrainzReleaseId = null,
+ Guid? musicBrainzReleaseGroupId = null,
+ Guid? musicBrainzReleaseArtistId = null,
+ DateTime? createdOnUtc = null,
+ DateTime? updatedOnUtc = null,
+ List? contributors = null,
+ List? ratings = null,
+ List? tracks = null,
+ bool includeMediaFormat = true,
+ bool includeBarcode = true,
+ bool includeCatalogNumber = true,
+ bool includeMusicBrainzReleaseId = true,
+ bool includeMusicBrainzReleaseGroupId = true,
+ bool includeMusicBrainzReleaseArtistId = true,
+ bool includeUpdatedOnUtc = true,
+ bool includeContributors = true,
+ bool includeRatings = true,
+ bool includeTracks = true)
+ {
+ return new AlbumResponse(
+ id ?? Guid.NewGuid(),
+ artistId ?? Guid.NewGuid(),
+ libraryId ?? Guid.NewGuid(),
+ metadata ?? _albumMetadataDtoFixture.Create(),
+ includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null,
+ includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null,
+ includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(10)) : null,
+ includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? Guid.NewGuid()) : null,
+ includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? Guid.NewGuid()) : null,
+ includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? Guid.NewGuid()) : null,
+ createdOnUtc ?? _faker.Date.Past().ToUniversalTime(),
+ 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);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs
new file mode 100644
index 00000000..a6cdd694
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs
@@ -0,0 +1,735 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Time;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DTO.Pagination;
+using Lumina.DataAccess.Common.Interceptors;
+using Lumina.DataAccess.Core.Repositories.MusicLibrary;
+using Lumina.DataAccess.Core.UoW;
+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 Microsoft.Data.Sqlite;
+using Microsoft.EntityFrameworkCore;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MusicLibrary;
+
+///
+/// Contains integration tests for the class, exercising it against a real SQLite database.
+///
+[ExcludeFromCodeCoverage]
+public class AlbumRepositoryTests
+{
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly TrackEntityFixture _trackEntityFixture = new();
+ private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new();
+ private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new();
+ private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new();
+ private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new();
+ private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new();
+ private readonly TagEntityFixture _tagEntityFixture = new();
+ private readonly GenreEntityFixture _genreEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
+
+ [Fact]
+ public async Task InsertAsync_WhenCalledWithAValidAlbum_ShouldPersistTheAlbumAndItsAggregate()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity album = BuildFullAlbum(artist.Id, libraryId, "A Night at the Opera");
+
+ // Act
+ Result result = await sut.InsertAsync(album, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(Result.Created, result.Value);
+ AlbumEntity? storedAlbum = await context.Albums
+ .AsNoTracking()
+ .Include(candidate => candidate.Ratings)
+ .Include(candidate => candidate.Tags)
+ .Include(candidate => candidate.Genres)
+ .Include(candidate => candidate.Contributors)
+ .Include(candidate => candidate.Tracks)
+ .ThenInclude(candidate => candidate.Moods)
+ .AsSplitQuery()
+ .FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
+ Assert.NotNull(storedAlbum);
+ Assert.Equal("A Night at the Opera", storedAlbum!.Title);
+ Assert.Single(storedAlbum.Ratings);
+ Assert.Equal(2, storedAlbum.Tags.Count);
+ Assert.Equal(2, storedAlbum.Genres.Count);
+ Assert.Single(storedAlbum.Contributors);
+ TrackEntity storedTrack = Assert.Single(storedAlbum.Tracks);
+ Assert.Equal(2, storedTrack.Moods.Count);
+ // Each tag and genre of the aggregate is stored exactly once.
+ Assert.Single(await context.Set().Where(tag => tag.Name == "album-tag-1").ToListAsync());
+ Assert.Single(await context.Set().Where(genre => genre.Name == "album-genre-1").ToListAsync());
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenAlbumWithTheSameIdAlreadyExists_ShouldReturnAlbumAlreadyExists()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-id-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity existingAlbum = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ context.Albums.Add(existingAlbum);
+ await context.SaveChangesAsync();
+
+ AlbumEntity album = _albumEntityFixture.Create(id: existingAlbum.Id, artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+
+ // Act
+ Result result = await sut.InsertAsync(album, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.AlbumAlreadyExists, result.FirstError);
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenTwoTracksOfTheSameRequestShareAPath_ShouldReturnTrackAlreadyExists()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-duprequest-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false);
+ album.Tracks =
+ [
+ _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false),
+ _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false)
+ ];
+
+ // Act
+ Result result = await sut.InsertAsync(album, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenATrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-storedpath-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity existingAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Existing");
+ context.Tracks.Add(_trackEntityFixture.Create(
+ albumId: existingAlbum.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false));
+ await context.SaveChangesAsync();
+
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)];
+
+ // Act
+ Result result = await sut.InsertAsync(album, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldPersistTheAlbum()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-otherlibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid firstLibraryId = Guid.NewGuid();
+ ArtistEntity firstArtist = await SeedArtistAsync(context, firstLibraryId);
+ AlbumEntity firstAlbum = await SeedAlbumAsync(context, firstLibraryId, firstArtist.Id, "First");
+ context.Tracks.Add(_trackEntityFixture.Create(
+ albumId: firstAlbum.Id, libraryId: firstLibraryId, path: "/music/queen/we-are-the-champions.flac", includeMetadata: false));
+ await context.SaveChangesAsync();
+
+ Guid secondLibraryId = Guid.NewGuid();
+ ArtistEntity secondArtist = await SeedArtistAsync(context, secondLibraryId);
+ AlbumEntity album = _albumEntityFixture.Create(artistId: secondArtist.Id, libraryId: secondLibraryId, includeTracks: false, includeMetadata: false);
+ album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: secondLibraryId, path: "/music/queen/we-are-the-champions.flac", includeMetadata: false)];
+
+ // Act
+ Result result = await sut.InsertAsync(album, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(Result.Created, result.Value);
+ AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
+ Assert.NotNull(storedAlbum);
+ Assert.Equal(secondLibraryId, storedAlbum!.LibraryId);
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenTagsAndGenresAlreadyExistByName_ShouldReuseTheStoredRows()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-reuse-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ context.Set().Add(_tagEntityFixture.Create(name: "ExistingTag"));
+ context.Set().Add(_genreEntityFixture.Create(name: "ExistingGenre"));
+ await context.SaveChangesAsync();
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ album.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
+ album.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
+ TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, includeMetadata: false);
+ track.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
+ track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
+ album.Tracks = [track];
+
+ // Act
+ Result result = await sut.InsertAsync(album, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ // The shared rows are reused instead of being duplicated.
+ Assert.Single(await context.Set().Where(tag => tag.Name == "ExistingTag").ToListAsync());
+ Assert.Single(await context.Set().Where(genre => genre.Name == "ExistingGenre").ToListAsync());
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTracks_ShouldPersistItOnce()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-shared-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().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);
+ TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
+ album.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")];
+ album.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")];
+ track.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")];
+ track.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")];
+ album.Tracks = [track];
+
+ // Act
+ Result result = await sut.InsertAsync(album, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(Result.Created, result.Value);
+ // The name shared by the album and its tracks is persisted exactly once.
+ Assert.Single(await context.Set().Where(tag => tag.Name == "SharedNewTag").ToListAsync());
+ Assert.Single(await context.Set().Where(genre => genre.Name == "SharedNewGenre").ToListAsync());
+ }
+
+ [Fact]
+ public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ Guid userId = Guid.NewGuid();
+ DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
+ using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ Guid contributorId = album.Contributors[0].Id;
+ DateTime contributorCreatedOnUtc = album.Contributors[0].CreatedOnUtc;
+ // Detach the seeded graph, so that the update must load the tracked album through its include chain instead of returning the already populated seeded instance.
+ context.ChangeTracker.Clear();
+ AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id);
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
+ Assert.NotNull(storedAlbum);
+ Assert.Null(storedAlbum!.UpdatedOnUtc);
+ AlbumContributorEntity storedContributor = Assert.Single(storedAlbum.Contributors);
+ Assert.Equal(contributorId, storedContributor.Id);
+ Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
+ Assert.Single(await context.Set().Where(tag => tag.Name == "album-tag-1").ToListAsync());
+ Assert.Single(await context.Set().Where(genre => genre.Name == "album-genre-1").ToListAsync());
+ }
+
+ [Fact]
+ public async Task UpdateAsync_WhenOnlyTheScalarValuesChanged_ShouldStampTheAlbumAndPreserveArtistAndLibrary()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-scalars-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ Guid userId = Guid.NewGuid();
+ DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
+ using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id);
+ incoming.Title = "A Night at the Opera (Remastered)";
+ incoming.ArtistId = Guid.NewGuid();
+ incoming.LibraryId = Guid.NewGuid();
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
+ Assert.NotNull(storedAlbum);
+ Assert.Equal("A Night at the Opera (Remastered)", storedAlbum!.Title);
+ // The stored identity is preserved and only the actual edit is stamped.
+ Assert.Equal(artist.Id, storedAlbum.ArtistId);
+ Assert.Equal(libraryId, storedAlbum.LibraryId);
+ Assert.Equal(utcNow, storedAlbum.UpdatedOnUtc);
+ Assert.Equal(userId, storedAlbum.UpdatedBy);
+ }
+
+ [Fact]
+ public async Task UpdateAsync_WhenRatingsAndContributorsChange_ShouldReconcileThem()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-owned-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ Guid keptMediaContributorId = Guid.NewGuid();
+ Guid removedMediaContributorId = Guid.NewGuid();
+ Guid addedMediaContributorId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ album.Ratings =
+ [
+ _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
+ _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10),
+ _audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20)
+ ];
+ album.Contributors =
+ [
+ _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer),
+ _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Composer)
+ ];
+ context.Albums.Add(album);
+ await context.SaveChangesAsync();
+
+ AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id);
+ incoming.Ratings =
+ [
+ _audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
+ _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10),
+ _audioRatingEntityFixture.Create(value: 1, maxValue: 5, source: AudioRatingSource.Discogs, voteCount: 5)
+ ];
+ incoming.Contributors =
+ [
+ _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer),
+ _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals)
+ ];
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ AlbumEntity? storedAlbum = await context.Albums
+ .AsNoTracking()
+ .Include(candidate => candidate.Ratings)
+ .Include(candidate => candidate.Contributors)
+ .FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
+ Assert.NotNull(storedAlbum);
+ Assert.Equal(3, storedAlbum!.Ratings.Count);
+ Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.MusicBrainz && rating.Value == 3M);
+ Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.User && rating.Value == 5M);
+ Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.Discogs && rating.Value == 1M);
+ Assert.DoesNotContain(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.LastFm);
+ Assert.Equal(2, storedAlbum.Contributors.Count);
+ Assert.DoesNotContain(storedAlbum.Contributors, contributor => contributor.MediaContributorId == removedMediaContributorId);
+ Assert.Contains(storedAlbum.Contributors, contributor => contributor.MediaContributorId == addedMediaContributorId);
+ }
+
+ [Fact]
+ public async Task GetByIdAsync_WhenAlbumExists_ShouldIncludeTheNavigationProperties()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera");
+
+ // Act
+ Result result = await sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ AlbumEntity retrievedAlbum = result.Value!;
+ Assert.NotNull(retrievedAlbum.Artist);
+ Assert.Equal(artist.Id, retrievedAlbum.Artist!.Id);
+ Assert.Single(retrievedAlbum.Ratings);
+ Assert.Equal(2, retrievedAlbum.Tags.Count);
+ Assert.Equal(2, retrievedAlbum.Genres.Count);
+ Assert.Single(retrievedAlbum.Contributors);
+ TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks);
+ Assert.Single(retrievedTrack.Ratings);
+ Assert.Equal(2, retrievedTrack.Genres.Count);
+ Assert.Equal(2, retrievedTrack.Moods.Count);
+ Assert.Equal(2, retrievedTrack.Isrcs.Count);
+ Assert.Single(retrievedTrack.Contributors);
+ }
+
+ [Fact]
+ public async Task GetByIdAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnAnUntrackedAlbum()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().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);
+ await context.SaveChangesAsync();
+ context.ChangeTracker.Clear();
+
+ // Act
+ Result result = await sut.GetByIdAsync(
+ album.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.NotNull(result.Value);
+ Assert.Empty(context.ChangeTracker.Entries());
+ }
+
+ [Fact]
+ public async Task GetAlbumsLiteByArtistIdAsync_WhenCalled_ShouldNotTrackTheEntities()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().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);
+ await context.SaveChangesAsync();
+ context.ChangeTracker.Clear();
+
+ // Act
+ Result> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Single(result.Value.Data);
+ Assert.Empty(context.ChangeTracker.Entries());
+ }
+
+ [Fact]
+ public async Task GetByArtistIdAsync_WhenCalled_ShouldReturnTheArtistAlbumsOrderedWithTheirCollections()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyartist-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity betaAlbum = await SeedFullAlbumAsync(context, libraryId, artist.Id, "Beta");
+ AlbumEntity alphaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Alpha");
+ ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(
+ artistId: otherArtist.Id, libraryId: libraryId, title: "Gamma", includeTracks: false, includeMetadata: false);
+ context.Albums.Add(albumOfAnotherArtist);
+ await context.SaveChangesAsync();
+
+ // Act
+ Result> result = await sut.GetByArtistIdAsync(artist.Id, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal([alphaAlbum.Id, betaAlbum.Id], result.Value.Select(album => album.Id));
+ AlbumEntity retrievedAlbum = result.Value.Single(album => album.Id == betaAlbum.Id);
+ Assert.Single(retrievedAlbum.Ratings);
+ Assert.Equal(2, retrievedAlbum.Tags.Count);
+ Assert.Equal(2, retrievedAlbum.Genres.Count);
+ Assert.Single(retrievedAlbum.Contributors);
+ TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks);
+ Assert.Equal(2, retrievedTrack.Moods.Count);
+ Assert.Single(retrievedTrack.Contributors);
+ }
+
+ [Fact]
+ public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationDataIsNull_ShouldReturnAllArtistAlbumsOrdered()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-null-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity betaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Beta");
+ AlbumEntity alphaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Alpha");
+ ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId);
+ AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(
+ artistId: otherArtist.Id, libraryId: libraryId, title: "Gamma", includeTracks: false, includeMetadata: false);
+ context.Albums.Add(albumOfAnotherArtist);
+ await context.SaveChangesAsync();
+
+ // Act
+ Result> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal([alphaAlbum.Id, betaAlbum.Id], result.Value.Data.Select(row => row.Id));
+ Assert.Equal(2, result.Value.Count);
+ Assert.Equal(1, result.Value.CurrentPage);
+ Assert.Equal(2, result.Value.PerPage);
+ }
+
+ [Theory]
+ [InlineData(1, 2, 1, 2)] // The first page is fully returned.
+ [InlineData(2, 2, 2, 2)] // A middle page is fully returned.
+ [InlineData(3, 2, 3, 1)] // The last page is partially returned.
+ [InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page.
+ public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount)
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-page-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ AlbumRepository sut = CreateAlbumRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId);
+ List albums = _albumEntityFixture.CreateMany(5);
+ for (int index = 0; index < albums.Count; index++)
+ {
+ albums[index].ArtistId = artist.Id;
+ albums[index].LibraryId = libraryId;
+ albums[index].Title = $"Album {index}";
+ albums[index].Tracks = [];
+ }
+ context.Albums.AddRange(albums);
+ await context.SaveChangesAsync();
+
+ PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage);
+
+ // Act
+ Result> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, paginationData, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(5, result.Value.Count);
+ Assert.Equal(3, result.Value.NumberOfPages);
+ Assert.Equal(expectedCurrentPage, result.Value.CurrentPage);
+ Assert.Equal(perPage, result.Value.PerPage);
+ Assert.Equal(expectedRowCount, result.Value.Data.Count);
+ }
+
+ ///
+ /// Creates an album repository backed by the provided context, wiring the real track repository.
+ ///
+ /// The context the repository operates on.
+ /// The created repository.
+ private static AlbumRepository CreateAlbumRepository(LuminaDbContext context)
+ {
+ return new AlbumRepository(context, new TrackRepository(context));
+ }
+
+ ///
+ /// Seeds an artist with no albums or contributors, so that the required foreign key of an album is satisfied.
+ ///
+ /// The context the artist is persisted through.
+ /// The Id of the library that owns the artist.
+ /// The persisted artist.
+ private async Task SeedArtistAsync(LuminaDbContext context, Guid libraryId)
+ {
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+ return artist;
+ }
+
+ ///
+ /// Seeds an album that belongs to the artist identified by .
+ ///
+ /// The context the album is persisted through.
+ /// The Id of the library that owns the album.
+ /// The Id of the artist that owns the album.
+ /// The title of the album.
+ /// The persisted album.
+ private async Task SeedAlbumAsync(LuminaDbContext context, Guid libraryId, Guid artistId, string title)
+ {
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false);
+ context.Albums.Add(album);
+ await context.SaveChangesAsync();
+ return album;
+ }
+
+ ///
+ /// Seeds an album with one track, including every related collection deterministically.
+ ///
+ /// The context the album is persisted through.
+ /// The Id of the library that owns the album.
+ /// The Id of the artist that owns the album.
+ /// The title of the album.
+ /// The persisted album.
+ private async Task SeedFullAlbumAsync(LuminaDbContext context, Guid libraryId, Guid artistId, string title)
+ {
+ AlbumEntity album = BuildFullAlbum(artistId, libraryId, title);
+ context.Albums.Add(album);
+ await context.SaveChangesAsync();
+ return album;
+ }
+
+ ///
+ /// Builds an album with one track, including every related collection deterministically, without persisting it.
+ ///
+ /// The Id of the artist that owns the album.
+ /// The Id of the library that owns the album.
+ /// The title of the album.
+ /// The created album.
+ private AlbumEntity BuildFullAlbum(Guid artistId, Guid libraryId, string title)
+ {
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false);
+ album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
+ album.Tags = [_tagEntityFixture.Create(name: "album-tag-1"), _tagEntityFixture.Create(name: "album-tag-2")];
+ album.Genres = [_genreEntityFixture.Create(name: "album-genre-1"), _genreEntityFixture.Create(name: "album-genre-2")];
+ album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)];
+ TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
+ track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)];
+ track.Tags = [_tagEntityFixture.Create(name: "track-tag-1"), _tagEntityFixture.Create(name: "track-tag-2")];
+ track.Genres = [_genreEntityFixture.Create(name: "track-genre-1"), _genreEntityFixture.Create(name: "track-genre-2")];
+ track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")];
+ track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")];
+ track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
+ album.Tracks = [track];
+ return album;
+ }
+
+ ///
+ /// Loads a detached copy of a stored album with the whole aggregate, so that it can be handed to the repository as the desired state of an edit.
+ ///
+ /// The context that tracks the stored album.
+ /// The Id of the album to load.
+ /// The detached copy of the album.
+ private static async Task LoadDetachedAlbumAsync(LuminaDbContext context, Guid albumId)
+ {
+ return await context.Albums
+ .AsNoTracking()
+ .Include(album => album.Ratings)
+ .Include(album => album.Tags)
+ .Include(album => album.Genres)
+ .Include(album => album.Contributors)
+ .Include(album => album.Tracks)
+ .ThenInclude(track => track.Ratings)
+ .Include(album => album.Tracks)
+ .ThenInclude(track => track.Genres)
+ .Include(album => album.Tracks)
+ .ThenInclude(track => track.Tags)
+ .Include(album => album.Tracks)
+ .ThenInclude(track => track.Moods)
+ .Include(album => album.Tracks)
+ .ThenInclude(track => track.Isrcs)
+ .Include(album => album.Tracks)
+ .ThenInclude(track => track.Contributors)
+ .AsSplitQuery()
+ .FirstAsync(album => album.Id == albumId);
+ }
+
+ ///
+ /// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
+ ///
+ /// The open in-memory SQLite connection that keeps the database alive for the duration of the test.
+ /// The Id of the user reported as the current user.
+ /// The current UTC time reported by the time provider.
+ /// The created context.
+ private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow)
+ {
+ ICurrentUserService currentUserService = Substitute.For();
+ currentUserService.UserId.Returns(userId);
+ IDateTimeProvider dateTimeProvider = Substitute.For();
+ dateTimeProvider.UtcNow.Returns(utcNow);
+ LuminaDbContext context = new(new DbContextOptionsBuilder()
+ .UseSqlite(anchorConnection.ConnectionString)
+ .AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider))
+ .Options);
+ context.Database.EnsureCreated();
+ return context;
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs
new file mode 100644
index 00000000..61082ddd
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs
@@ -0,0 +1,397 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class AddAlbumEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+ private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public AddAlbumEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenCalledWithValidData_ShouldAddAlbum()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(
+ metadata: _albumMetadataDtoFixture.Create(title: "News of the World"),
+ contributors: [],
+ ratings: [],
+ tracks: []);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ AlbumResponse? albumResponse = JsonSerializer.Deserialize(content, _jsonOptions);
+ Assert.NotNull(albumResponse);
+ Assert.Equal(artistId, albumResponse!.ArtistId);
+ Assert.Equal(libraryId, albumResponse.LibraryId);
+ Assert.Equal("News of the World", albumResponse.Metadata.Title);
+
+ Assert.NotNull(response.Headers.Location);
+ Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumResponse.Id}", response.Headers.Location!.ToString());
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenMetadataIsMissing_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(includeMetadata: false, contributors: [], ratings: [], tracks: []);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Metadata.MetadataCannotBeNull.Description);
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenTitleIsMissing_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(
+ metadata: _albumMetadataDtoFixture.Create(includeTitle: false),
+ contributors: [],
+ ratings: [],
+ tracks: []);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Music.AlbumTitleCannotBeEmpty.Description);
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutDisclosingIt()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
+ Guid otherLibraryId = Guid.NewGuid();
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
+ Guid artistId = await SeedArtistWithAlbumAsync(otherLibraryId);
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync(url, request);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Library.LibraryIdCannotBeEmpty.Description);
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, Errors.Music.ArtistIdCannotBeEmpty.Description);
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid artistId = await SeedArtistWithAlbumAsync(libraryId);
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
+
+ // Act & Assert
+ Exception? exception = await Record.ExceptionAsync(async () =>
+ await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request, cts.Token));
+ Assert.Null(exception);
+ }
+
+ ///
+ /// Seeds a music library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds an artist that owns a single album, both belonging to .
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The Id of the seeded artist.
+ private async Task SeedArtistWithAlbumAsync(Guid libraryId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return artistId;
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
+ {
+ await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
+ }
+
+ ///
+ /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected HTTP status code.
+ /// The expected problem title.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ /// The expected problem type URI.
+ private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
+ {
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
+ Assert.Equal(expectedType, problemDetails["type"].GetString());
+ Assert.Equal(expectedTitle, problemDetails["title"].GetString());
+ Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs
new file mode 100644
index 00000000..e8b9119e
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs
@@ -0,0 +1,336 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteAlbumEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public DeleteAlbumEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenAlbumBelongsToAnOwnedArtist_ShouldDeleteTheAlbum()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, Guid albumId, Guid otherAlbumId) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Null(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId));
+ // The sibling album of the artist is preserved.
+ Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == otherAlbumId));
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, _, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "AlbumNotFound", url);
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, _, Guid albumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenAlbumRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, Guid artistId, Guid albumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(userId);
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedLibraryArtistWithTwoAlbumsAsync(otherUserId);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
+ }
+
+ ///
+ /// Seeds a music library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist that owns two albums.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library, artist and the two albums.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid otherAlbumId)> SeedLibraryArtistWithTwoAlbumsAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid otherAlbumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ AlbumEntity otherAlbum = _albumEntityFixture.Create(id: otherAlbumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId, otherAlbumId);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
+ {
+ await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
+ }
+
+ ///
+ /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected HTTP status code.
+ /// The expected problem title.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ /// The expected problem type URI.
+ private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
+ {
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
+ Assert.Equal(expectedType, problemDetails["type"].GetString());
+ Assert.Equal(expectedTitle, problemDetails["title"].GetString());
+ Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs
new file mode 100644
index 00000000..cbffecce
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs
@@ -0,0 +1,335 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetAlbumEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetAlbumEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenAlbumBelongsToAnOwnedLibrary_ShouldReturnAlbumDetails()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ AlbumResponse? album = JsonSerializer.Deserialize(content, _jsonOptions);
+ Assert.NotNull(album);
+ Assert.Equal(albumId, album!.Id);
+ Assert.Equal(artistId, album.ArtistId);
+ Assert.Equal(libraryId, album.LibraryId);
+ Assert.Equal("A Night at the Opera", album.Metadata.Title);
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+ string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "AlbumNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, _, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+ // The route artist id is enforced, so an album of another artist is reported as not found, without disclosing that it exists.
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "AlbumNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenAlbumRequestedThroughDifferentLibrary_ShouldReturnAlbumNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums/{albumId}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "AlbumNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, "News of the World");
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist and one of its albums.
+ ///
+ /// The Id of the user that owns the library.
+ /// The title of the seeded album.
+ /// The Ids of the seeded library, artist and album.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
+ {
+ await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
+ }
+
+ ///
+ /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected HTTP status code.
+ /// The expected problem title.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ /// The expected problem type URI.
+ private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
+ {
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
+ Assert.Equal(expectedType, problemDetails["type"].GetString());
+ Assert.Equal(expectedTitle, problemDetails["title"].GetString());
+ Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs
new file mode 100644
index 00000000..87660b59
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs
@@ -0,0 +1,330 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetAlbumTracksEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly TrackEntityFixture _trackEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetAlbumTracksEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task GetAlbumTracks_WhenAlbumHasTracks_ShouldReturnTrackDetails()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? tracks = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(tracks);
+ TrackResponse track = Assert.Single(tracks!);
+ Assert.Equal("Bohemian Rhapsody", track.Metadata.Title);
+ }
+
+ [Fact]
+ public async Task GetAlbumTracks_WhenAlbumHasNoTracks_ShouldReturnEmptyCollection()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? tracks = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(tracks);
+ Assert.Empty(tracks!);
+ }
+
+ [Fact]
+ public async Task GetAlbumTracks_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+ string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "AlbumNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetAlbumTracks_WhenAlbumRequestedThroughDifferentArtist_ShouldReturnAlbumNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, _, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{albumId}/tracks";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "AlbumNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetAlbumTracks_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
+ }
+
+ [Fact]
+ public async Task GetAlbumTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetAlbumTracks_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist and one of its albums.
+ ///
+ /// The Id of the user that owns the library.
+ /// The title of the seeded album.
+ /// The Ids of the seeded library, artist and album.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId);
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist, one of its albums and one of its tracks.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library, artist, album and track.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/bohemian-rhapsody-{Guid.NewGuid():N}.flac", title: "Bohemian Rhapsody", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId, trackId);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
+ {
+ await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
+ }
+
+ ///
+ /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected HTTP status code.
+ /// The expected problem title.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ /// The expected problem type URI.
+ private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
+ {
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
+ Assert.Equal(expectedType, problemDetails["type"].GetString());
+ Assert.Equal(expectedTitle, problemDetails["title"].GetString());
+ Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs
new file mode 100644
index 00000000..bd61749b
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs
@@ -0,0 +1,316 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetAlbumTracksLiteEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly TrackEntityFixture _trackEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetAlbumTracksLiteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task GetAlbumTracksLite_WhenAlbumHasTracks_ShouldReturnTrackLiteDetails()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ PaginatedResponse? tracks = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(tracks);
+ Assert.Equal(1, tracks!.Count);
+ TrackLiteResponse track = Assert.Single(tracks.Data);
+ Assert.Equal("Bohemian Rhapsody", track.Title);
+ }
+
+ [Fact]
+ public async Task GetAlbumTracksLite_WhenAlbumHasNoTracks_ShouldReturnEmptyPaginatedResponse()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ PaginatedResponse? tracks = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(tracks);
+ Assert.Empty(tracks!.Data);
+ Assert.Equal(0, tracks.Count);
+ }
+
+ [Fact]
+ public async Task GetAlbumTracksLite_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+ string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/tracks/lite";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "AlbumNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetAlbumTracksLite_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/tracks/lite";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
+ }
+
+ [Fact]
+ public async Task GetAlbumTracksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetAlbumTracksLite_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/not-a-guid/tracks/lite";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist and one of its albums.
+ ///
+ /// The Id of the user that owns the library.
+ /// The title of the seeded album.
+ /// The Ids of the seeded library, artist and album.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId);
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist, one of its albums and one of its tracks.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library, artist, album and track.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/bohemian-rhapsody-{Guid.NewGuid():N}.flac", title: "Bohemian Rhapsody", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId, trackId);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
+ {
+ await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
+ }
+
+ ///
+ /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected HTTP status code.
+ /// The expected problem title.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ /// The expected problem type URI.
+ private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
+ {
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
+ Assert.Equal(expectedType, problemDetails["type"].GetString());
+ Assert.Equal(expectedTitle, problemDetails["title"].GetString());
+ Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs
new file mode 100644
index 00000000..2bad9145
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs
@@ -0,0 +1,344 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateAlbumEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+ private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public UpdateAlbumEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenCalledByOwnerWithValidData_ShouldUpdateAlbumAndPersistChanges()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(
+ metadata: _albumMetadataDtoFixture.Create(title: "Updated Album"),
+ contributors: [],
+ ratings: []);
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ AlbumResponse? albumResponse = JsonSerializer.Deserialize(content, _jsonOptions);
+ Assert.NotNull(albumResponse);
+ Assert.Equal(albumId, albumResponse!.Id);
+ Assert.Equal("Updated Album", albumResponse.Metadata.Title);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ AlbumEntity storedAlbum = dbContext.Albums.Single(album => album.Id == albumId);
+ Assert.Equal("Updated Album", storedAlbum.Title);
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
+
+ // Assert
+ await AssertNotFoundAsync(response, "AlbumNotFound", url);
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId, "News of the World");
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync(url, request);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenMetadataIsMissing_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(includeMetadata: false, contributors: [], ratings: []);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "MetadataCannotBeNull");
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId, "A Night at the Opera");
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/not-a-guid";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
+ }
+
+ ///
+ /// Seeds a music library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist and one of its albums.
+ ///
+ /// The Id of the user that owns the library.
+ /// The title of the seeded album.
+ /// The Ids of the seeded library, artist and album.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId, string albumTitle)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
+ {
+ await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
+ }
+
+ ///
+ /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected HTTP status code.
+ /// The expected problem title.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ /// The expected problem type URI.
+ private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
+ {
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
+ Assert.Equal(expectedType, problemDetails["type"].GetString());
+ Assert.Equal(expectedTitle, problemDetails["title"].GetString());
+ Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs
new file mode 100644
index 00000000..c3d08c2c
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs
@@ -0,0 +1,242 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class AddAlbumEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public AddAlbumEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenUnauthorized_ShouldNotLeakSensitiveData()
+ {
+ // Arrange
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", request);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task AddAlbum_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
+ {
+ // Arrange
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
+
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task AddAlbum_WithSQLInjectionInArtistRouteId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
+ {
+ // Arrange
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
+
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task AddAlbum_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle)
+ {
+ // Arrange
+ (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ (Guid libraryId, Guid artistId) = await SeedLibraryArtistAndAlbumAsync(userId);
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(
+ metadata: _albumMetadataDtoFixture.Create(title: maliciousTitle),
+ contributors: [],
+ ratings: [],
+ tracks: []);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
+
+ // Assert
+ // The malicious title passes validation, reaches the parameterized insert, and is persisted verbatim: if it were
+ // concatenated into raw SQL, the insert would fail and the album would not be created.
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Equal(2, await dbContext.Albums.CountAsync(album => album.LibraryId == libraryId));
+
+ }
+
+ [Fact]
+ public async Task AddAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
+ {
+ // Arrange
+ HttpClient ownerClient = _apiFactory.CreateClient();
+ (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
+ _seededUsernames.Add(ownerUsername);
+ (Guid libraryId, Guid artistId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
+
+ (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(requesterUsername);
+ AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist that owns one album.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library and artist.
+ private async Task<(Guid libraryId, Guid artistId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId);
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs
new file mode 100644
index 00000000..c22f6d2d
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs
@@ -0,0 +1,262 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteAlbumEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public DeleteAlbumEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task DeleteAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task DeleteAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task DeleteAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistWithTwoAlbumsAsync(otherUserId);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+
+ }
+
+ [Fact]
+ public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(actingUsername);
+ (Guid ownLibraryId, _, _) = await SeedLibraryArtistWithTwoAlbumsAsync(actingUserId);
+
+ // The album lives in a library owned by another user, and is referenced through the acting user's own library route.
+ HttpClient victimClient = _apiFactory.CreateClient();
+ (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
+ _seededUsernames.Add(victimUsername);
+ (_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistWithTwoAlbumsAsync(victimUserId);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
+
+ // The other user's album is untouched.
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId));
+
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded other user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return userId;
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist that owns two albums.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library, artist and the first album.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistWithTwoAlbumsAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid otherAlbumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ AlbumEntity otherAlbum = _albumEntityFixture.Create(id: otherAlbumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId);
+ }
+
+ ///
+ /// Disposes the API factory resources.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs
new file mode 100644
index 00000000..29503bcf
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs
@@ -0,0 +1,219 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetAlbumEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetAlbumEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task GetAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task GetAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task GetAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Fact]
+ public async Task GetAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded other user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return userId;
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist and one of its albums.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library, artist and album.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId);
+ }
+
+ ///
+ /// Disposes the API factory resources.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs
new file mode 100644
index 00000000..1506e1fd
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs
@@ -0,0 +1,222 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetAlbumTracksEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly TrackEntityFixture _trackEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetAlbumTracksEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ }
+
+ [Fact]
+ public async Task GetAlbumTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task GetAlbumTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task GetAlbumTracks_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task GetAlbumTracks_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Fact]
+ public async Task GetAlbumTracks_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded other user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return userId;
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist, one of its albums and one of its tracks.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library, artist, album and track.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac", title: "We Are the Champions", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId, trackId);
+ }
+
+ ///
+ /// Disposes the API factory resources.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs
new file mode 100644
index 00000000..0aaa8260
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs
@@ -0,0 +1,222 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetAlbumTracksLiteEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly TrackEntityFixture _trackEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetAlbumTracksLiteEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ }
+
+ [Fact]
+ public async Task GetAlbumTracksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task GetAlbumTracksLite_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task GetAlbumTracksLite_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/lite");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task GetAlbumTracksLite_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/lite");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+
+ }
+
+ [Fact]
+ public async Task GetAlbumTracksLite_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded other user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return userId;
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist, one of its albums and one of its tracks.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library, artist, album and track.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac", title: "We Are the Champions", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId, trackId);
+ }
+
+ ///
+ /// Disposes the API factory resources.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs
new file mode 100644
index 00000000..15190c19
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs
@@ -0,0 +1,294 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateAlbumEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public UpdateAlbumEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+
+ // Act
+ HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(401, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenUnauthorized_ShouldNotLeakSensitiveData()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+
+ // Act
+ HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", request);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task UpdateAlbum_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousTitle)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: maliciousTitle), contributors: [], ratings: []);
+
+ // Act
+ HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
+
+ // Assert
+ // The malicious title passes validation, reaches the parameterized update, and is persisted verbatim: if it were
+ // concatenated into raw SQL, the update would fail and the album would not be updated.
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
+ Assert.NotNull(storedAlbum);
+ Assert.Equal(maliciousTitle, storedAlbum!.Title);
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task UpdateAlbum_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+
+ // Act
+ HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", request);
+
+ // Assert
+ await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty");
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task UpdateAlbum_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+
+ // Act
+ HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}", request);
+
+ // Assert
+ await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty");
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task UpdateAlbum_WithSQLInjectionInAlbumRouteId_ShouldRemainSecure(string maliciousAlbumId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+
+ // Act
+ HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}", request);
+
+ // Assert
+ await AssertCleanValidationErrorAsync(response, maliciousAlbumId, "AlbumIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
+ {
+ // Arrange
+ HttpClient ownerClient = _apiFactory.CreateClient();
+ (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
+ _seededUsernames.Add(ownerUsername);
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
+
+ HttpClient requesterClient = _apiFactory.CreateClient();
+ (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
+ _seededUsernames.Add(requesterUsername);
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
+
+ // Act
+ HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ }
+
+ [Fact]
+ public async Task UpdateAlbum_WhenResourceBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(actingUsername);
+ (Guid ownLibraryId, _, _) = await SeedLibraryArtistAndAlbumAsync(actingUserId);
+
+ // The resource lives in a library owned by another user, and is referenced through the acting user's own library route.
+ HttpClient victimClient = _apiFactory.CreateClient();
+ (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
+ _seededUsernames.Add(victimUsername);
+ (_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistAndAlbumAsync(victimUserId);
+ UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: "Hijacked"), contributors: [], ratings: []);
+
+ // Act
+ HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
+
+ // The other user's album is untouched.
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId);
+ Assert.NotNull(storedAlbum);
+ Assert.Equal("News of the World", storedAlbum.Title);
+ }
+
+ ///
+ /// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
+ ///
+ /// The HTTP response to assert.
+ /// The injected payload that must never be echoed back.
+ /// The validation error code expected in the response.
+ private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(injectedPayload, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal);
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist and one of its albums.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library, artist and album.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId);
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public void Dispose()
+ {
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMappingTests.cs
new file mode 100644
index 00000000..f327f806
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMappingTests.cs
@@ -0,0 +1,211 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
+using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
+using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack;
+using Lumina.Contracts.Fixtures.Core.DTO.Common;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class AddAlbumCommandMappingTests
+{
+ private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new();
+ private readonly AddTrackCommandFixture _addTrackCommandFixture = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly GenreDtoFixture _genreDtoFixture = new();
+ private readonly IsrcDtoFixture _isrcDtoFixture = new();
+ private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
+
+ [Fact]
+ public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly()
+ {
+ // Arrange
+ AddAlbumCommand command = _addAlbumCommandFixture.Create();
+
+ // Act
+ Result result = command.ToDomainEntity();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Album album = result.Value;
+ Assert.Equal(command.Metadata!.Title, album.Metadata.Title);
+ Assert.Equal(command.MediaFormat, album.MediaFormat.Value);
+ Assert.Equal(command.Barcode, album.Barcode.Value.Value);
+ Assert.Equal(command.CatalogNumber, album.CatalogNumber.Value);
+ Assert.Equal(command.MusicBrainzReleaseId, album.MusicBrainzReleaseId.Value.Value);
+ Assert.Equal(command.MusicBrainzReleaseGroupId, album.MusicBrainzReleaseGroupId.Value.Value);
+ Assert.Equal(command.MusicBrainzReleaseArtistId, album.MusicBrainzReleaseArtistId.Value.Value);
+ Assert.Equal(command.Contributors!.Count, album.Contributors.Count);
+ Assert.Equal(command.Ratings!.Count, album.Ratings.Count);
+ Assert.Equal(command.Tracks!.Count, album.Tracks.Count);
+ }
+
+ [Fact]
+ public void ToDomainEntity_WhenAlbumIdIsProvided_ShouldReuseTheProvidedAlbumId()
+ {
+ // Arrange
+ Guid albumId = Guid.NewGuid();
+ AddAlbumCommand command = _addAlbumCommandFixture.Create(albumId: albumId);
+
+ // Act
+ Result result = command.ToDomainEntity();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(albumId, result.Value.Id.Value);
+ }
+
+ [Fact]
+ public void ToDomainEntity_WhenAlbumIdIsNotProvided_ShouldMintANewAlbumId()
+ {
+ // Arrange
+ AddAlbumCommand firstCommand = _addAlbumCommandFixture.Create();
+ AddAlbumCommand secondCommand = _addAlbumCommandFixture.Create();
+
+ // Act
+ Result firstResult = firstCommand.ToDomainEntity();
+ Result