diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowFixture.cs
new file mode 100644
index 00000000..671ca538
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowFixture.cs
@@ -0,0 +1,46 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ArtistLiteRowFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the artist.
+ /// Optional. The name of the artist.
+ /// The created .
+ public ArtistLiteRow Create(
+ Guid? id = null,
+ string? name = null)
+ {
+ return new ArtistLiteRow
+ {
+ Id = id ?? _faker.Random.Guid(),
+ Name = name ?? _faker.Name.FullName()
+ };
+ }
+
+ ///
+ /// 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/ArtistEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntityFixture.cs
index fc730f78..db9dedae 100644
--- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntityFixture.cs
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntityFixture.cs
@@ -24,8 +24,12 @@ public class ArtistEntityFixture
/// Optional. The Id of the artist.
/// Optional. The Id of the media library that owns the artist.
/// Optional. The name of the artist.
+ /// Optional. The website of the artist.
+ /// Optional. The MusicBrainz identifier of the artist.
/// Optional. The albums of the artist.
/// Whether the artist should own a generated album, or no album at all.
+ /// Whether the website should be included, or forced to .
+ /// Whether the MusicBrainz identifier should be included, or forced to .
/// Whether the artist should own a generated media contributor, or none at all.
/// Whether the owned metadata collections of the generated album should be included, or forced to empty collections.
/// The created .
@@ -33,8 +37,12 @@ public class ArtistEntityFixture
Guid? id = null,
Guid? libraryId = null,
string? name = null,
+ string? website = null,
+ Guid? musicBrainzArtistId = null,
List? albums = null,
bool includeAlbums = true,
+ bool includeWebsite = true,
+ bool includeMusicBrainzArtistId = true,
bool includeContributors = true,
bool includeMetadata = true)
{
@@ -53,8 +61,8 @@ public class ArtistEntityFixture
UpdatedBy = null
})
.RuleFor(x => x.Name, f => name ?? f.Name.FullName())
- .RuleFor(x => x.Website, f => f.Internet.Url())
- .RuleFor(x => x.MusicBrainzArtistId, f => f.Random.Guid())
+ .RuleFor(x => x.Website, f => includeWebsite ? (website ?? f.Internet.Url()) : null)
+ .RuleFor(x => x.MusicBrainzArtistId, f => includeMusicBrainzArtistId ? (musicBrainzArtistId ?? f.Random.Guid()) : null)
.RuleFor(x => x.Albums, resolvedAlbums)
.RuleFor(x => x.Contributors, f => includeContributors ? _artistContributorEntityFixture.CreateMany(f.Random.Number(1, 3), artistId: resolvedId) : [])
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandFixture.cs
new file mode 100644
index 00000000..39e59696
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandFixture.cs
@@ -0,0 +1,86 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist;
+using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class AddArtistCommandFixture
+{
+ private readonly Faker _faker = new();
+ private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+
+ ///
+ /// Creates a random valid command to add an artist.
+ ///
+ /// Optional. The Id of the media library the artist belongs to, taken from the route.
+ /// Optional. The name of the artist.
+ /// Optional. The website of the artist.
+ /// Optional. The MusicBrainz identifier of the artist.
+ /// Optional. The media contributors that make up the artist.
+ /// Optional. The albums of the artist, each with its own tracks.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the name should be included, or forced to .
+ /// Whether the website should be included, or forced to .
+ /// Whether the MusicBrainz identifier should be included, or forced to .
+ /// Whether the contributors should be included, or forced to .
+ /// Whether the albums should be included, or forced to .
+ /// The created command to add an artist.
+ public AddArtistCommand Create(
+ string? libraryId = null,
+ string? name = null,
+ string? website = null,
+ Guid? musicBrainzArtistId = null,
+ List? contributors = null,
+ List? albums = null,
+ bool includeLibraryId = true,
+ bool includeName = true,
+ bool includeWebsite = true,
+ bool includeMusicBrainzArtistId = true,
+ bool includeContributors = true,
+ bool includeAlbums = true)
+ {
+ string? resolvedLibraryId = includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null;
+
+ return new AddArtistCommand(
+ resolvedLibraryId,
+ includeName ? (name ?? _faker.Name.FullName()) : null,
+ includeWebsite ? (website ?? _faker.Internet.Url()) : null,
+ includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null,
+ includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
+ includeAlbums ? (albums ?? GenerateAlbums(resolvedLibraryId)) : 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 albums of the artist, tied to the artist's library identifier.
+ ///
+ /// The Id of the media library the albums belong to.
+ /// The generated albums.
+ private List GenerateAlbums(string? libraryId)
+ {
+ return [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _addAlbumCommandFixture.Create(libraryId: libraryId))];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandFixture.cs
new file mode 100644
index 00000000..d7682aa1
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandFixture.cs
@@ -0,0 +1,45 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteArtistCommandFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the artist belongs to, taken from the route.
+ /// Optional. The Id of the artist 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 .
+ /// The created .
+ public DeleteArtistCommand Create(
+ string? libraryId = null,
+ string? artistId = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true)
+ {
+ return new DeleteArtistCommand(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? 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/Artists/Commands/UpdateArtist/UpdateArtistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandFixture.cs
new file mode 100644
index 00000000..43137c90
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandFixture.cs
@@ -0,0 +1,91 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist;
+using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateArtistCommandFixture
+{
+ private readonly Faker _faker = new();
+ private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+
+ ///
+ /// Creates a random valid command to update an artist.
+ ///
+ /// Optional. The Id of the media library the artist belongs to, taken from the route.
+ /// Optional. The Id of the artist, taken from the route.
+ /// Optional. The name of the artist.
+ /// Optional. The website of the artist.
+ /// Optional. The MusicBrainz identifier of the artist.
+ /// Optional. The media contributors that make up the artist.
+ /// Optional. The albums of the artist, each with its own tracks.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the name should be included, or forced to .
+ /// Whether the website should be included, or forced to .
+ /// Whether the MusicBrainz identifier should be included, or forced to .
+ /// Whether the contributors should be included, or forced to .
+ /// Whether the albums should be included, or forced to .
+ /// The created command to update an artist.
+ public UpdateArtistCommand Create(
+ string? libraryId = null,
+ string? artistId = null,
+ string? name = null,
+ string? website = null,
+ Guid? musicBrainzArtistId = null,
+ List? contributors = null,
+ List? albums = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeName = true,
+ bool includeWebsite = true,
+ bool includeMusicBrainzArtistId = true,
+ bool includeContributors = true,
+ bool includeAlbums = true)
+ {
+ string? resolvedLibraryId = includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null;
+
+ return new UpdateArtistCommand(
+ resolvedLibraryId,
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
+ includeName ? (name ?? _faker.Name.FullName()) : null,
+ includeWebsite ? (website ?? _faker.Internet.Url()) : null,
+ includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null,
+ includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
+ includeAlbums ? (albums ?? GenerateAlbums(resolvedLibraryId)) : 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 albums of the artist, tied to the artist's library identifier.
+ ///
+ /// The Id of the media library the albums belong to.
+ /// The generated albums.
+ private List GenerateAlbums(string? libraryId)
+ {
+ return [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _addAlbumCommandFixture.Create(libraryId: libraryId))];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryFixture.cs
new file mode 100644
index 00000000..06d3858a
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryFixture.cs
@@ -0,0 +1,45 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistQueryFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the artist belongs to, taken from the route.
+ /// Optional. The Id of the artist 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 .
+ /// The created .
+ public GetArtistQuery Create(
+ string? libraryId = null,
+ string? artistId = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true)
+ {
+ return new GetArtistQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? 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/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryFixture.cs
new file mode 100644
index 00000000..ef0df975
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryFixture.cs
@@ -0,0 +1,45 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistAlbumsQueryFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the artist belongs to, taken from the route.
+ /// Optional. The Id of the artist whose albums 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 .
+ /// The created .
+ public GetArtistAlbumsQuery Create(
+ string? libraryId = null,
+ string? artistId = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true)
+ {
+ return new GetArtistAlbumsQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? 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/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryFixture.cs
new file mode 100644
index 00000000..bb13fe01
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryFixture.cs
@@ -0,0 +1,54 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite;
+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.Artists.Queries.GetArtistAlbumsLite;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistAlbumsLiteQueryFixture
+{
+ private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the artist belongs to, taken from the route.
+ /// Optional. The Id of the artist whose albums 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 pagination data should be included, or forced to .
+ /// The created .
+ public GetArtistAlbumsLiteQuery Create(
+ string? libraryId = null,
+ string? artistId = null,
+ PaginationDataDto? paginationData = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includePaginationData = true)
+ {
+ return new GetArtistAlbumsLiteQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? 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.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryFixture.cs
new file mode 100644
index 00000000..f8a2c06b
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryFixture.cs
@@ -0,0 +1,56 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists;
+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.Artists.Queries.GetArtists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistsQueryFixture
+{
+ private readonly Faker _faker = new();
+ private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library whose artists are retrieved, taken from the route.
+ /// Optional. The pagination data of the query.
+ /// Optional. The search term used to filter the artists by name.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the pagination data should be included, or forced to .
+ /// Whether the search term should be included, or forced to .
+ /// The created .
+ public GetArtistsQuery Create(
+ string? libraryId = null,
+ PaginationDataDto? paginationData = null,
+ string? searchTerm = null,
+ bool includeLibraryId = true,
+ bool includePaginationData = true,
+ bool includeSearchTerm = true)
+ {
+ return new GetArtistsQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null,
+ includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : 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/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryFixture.cs
new file mode 100644
index 00000000..7e6ddb02
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryFixture.cs
@@ -0,0 +1,56 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite;
+using Lumina.Application.Fixtures.Common.DTO.Pagination;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistsLiteQueryFixture
+{
+ private readonly Faker _faker = new();
+ private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library whose artists are retrieved, taken from the route.
+ /// Optional. The pagination data of the query.
+ /// Optional. The search term used to filter the artists by name.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the pagination data should be included, or forced to .
+ /// Whether the search term should be included, or forced to .
+ /// The created .
+ public GetArtistsLiteQuery Create(
+ string? libraryId = null,
+ PaginationDataDto? paginationData = null,
+ string? searchTerm = null,
+ bool includeLibraryId = true,
+ bool includePaginationData = true,
+ bool includeSearchTerm = true)
+ {
+ return new GetArtistsLiteQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null,
+ includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : 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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestFixture.cs
new file mode 100644
index 00000000..df2aa7a4
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestFixture.cs
@@ -0,0 +1,69 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class AddArtistRequestFixture
+{
+ private readonly Faker _faker = new();
+ private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+
+ ///
+ /// Creates a random valid request to add an artist.
+ ///
+ /// Optional. The name of the artist.
+ /// Optional. The website of the artist.
+ /// Optional. The MusicBrainz identifier of the artist.
+ /// Optional. The media contributors that make up the artist.
+ /// Optional. The albums of the artist.
+ /// Whether the name should be included, or forced to .
+ /// Whether the website should be included, or forced to .
+ /// Whether the MusicBrainz artist Id should be included, or forced to .
+ /// Whether the contributors list should be included, or forced to .
+ /// Whether the albums list should be included, or forced to .
+ /// The created request to add an artist.
+ public AddArtistRequest Create(
+ string? name = null,
+ string? website = null,
+ Guid? musicBrainzArtistId = null,
+ List? contributors = null,
+ List? albums = null,
+ bool includeName = true,
+ bool includeWebsite = true,
+ bool includeMusicBrainzArtistId = true,
+ bool includeContributors = true,
+ bool includeAlbums = true)
+ {
+ return new AddArtistRequest(
+ includeName ? (name ?? _faker.Name.FullName()) : null,
+ includeWebsite ? (website ?? _faker.Internet.Url()) : null,
+ includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null,
+ includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null,
+ includeAlbums ? (albums ?? _addAlbumRequestFixture.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/Artists/GetArtistAlbumsLiteRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestFixture.cs
new file mode 100644
index 00000000..0382c0ac
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestFixture.cs
@@ -0,0 +1,47 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistAlbumsLiteRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid request to get the lightweight read models of the albums of an artist.
+ ///
+ /// Optional. The page of results to retrieve.
+ /// Optional. The maximum number of albums to retrieve per page.
+ /// Whether the current page should be included, or forced to .
+ /// Whether the per page count should be included, or forced to .
+ /// The created request to get the lightweight read models of the albums of an artist.
+ public GetArtistAlbumsLiteRequest Create(
+ int? currentPage = null,
+ int? perPage = null,
+ bool includeCurrentPage = true,
+ bool includePerPage = true)
+ {
+ return new GetArtistAlbumsLiteRequest(
+ includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null,
+ includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : 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/Artists/GetArtistsLiteRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestFixture.cs
new file mode 100644
index 00000000..c513da38
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestFixture.cs
@@ -0,0 +1,52 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistsLiteRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid request to get the lightweight read models of the artists of a media library.
+ ///
+ /// Optional. The page of results to retrieve.
+ /// Optional. The maximum number of artists to retrieve per page.
+ /// Optional. The search term used to filter the artists by name.
+ /// Whether the current page should be included, or forced to .
+ /// Whether the per page count should be included, or forced to .
+ /// Whether the search term should be included, or forced to .
+ /// The created request to get the lightweight read models of the artists of a media library.
+ public GetArtistsLiteRequest Create(
+ int? currentPage = null,
+ int? perPage = null,
+ string? searchTerm = null,
+ bool includeCurrentPage = true,
+ bool includePerPage = true,
+ bool includeSearchTerm = true)
+ {
+ return new GetArtistsLiteRequest(
+ includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null,
+ includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null,
+ includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : null);
+ }
+
+ ///
+ /// 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/Artists/GetArtistsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestFixture.cs
new file mode 100644
index 00000000..1698b9e7
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestFixture.cs
@@ -0,0 +1,52 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistsRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid request to get the artists of a media library.
+ ///
+ /// Optional. The page of results to retrieve.
+ /// Optional. The maximum number of artists to retrieve per page.
+ /// Optional. The search term used to filter the artists by name.
+ /// Whether the current page should be included, or forced to .
+ /// Whether the per page count should be included, or forced to .
+ /// Whether the search term should be included, or forced to .
+ /// The created request to get the artists of a media library.
+ public GetArtistsRequest Create(
+ int? currentPage = null,
+ int? perPage = null,
+ string? searchTerm = null,
+ bool includeCurrentPage = true,
+ bool includePerPage = true,
+ bool includeSearchTerm = true)
+ {
+ return new GetArtistsRequest(
+ includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null,
+ includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null,
+ includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : 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/Artists/UpdateArtistAlbumRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestFixture.cs
new file mode 100644
index 00000000..89389dba
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestFixture.cs
@@ -0,0 +1,105 @@
+#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.Artists;
+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.Artists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateArtistAlbumRequestFixture
+{
+ private readonly Faker _faker = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly UpdateArtistTrackRequestFixture _updateArtistTrackRequestFixture = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+ private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new();
+
+ ///
+ /// Creates a random valid request to update an album of an artist.
+ ///
+ /// Optional. The Id of the album, when the album already exists.
+ /// 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 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 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 .
+ /// The created request to update an album of an artist.
+ public UpdateArtistAlbumRequest Create(
+ Guid? 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,
+ List? tracks = null,
+ 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,
+ bool includeTracks = true)
+ {
+ return new UpdateArtistAlbumRequest(
+ includeAlbumId ? (albumId ?? _faker.Random.Guid()) : null,
+ includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null,
+ includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null,
+ includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null,
+ includeCatalogNumber ? (catalogNumber ?? _faker.Random.String2(_faker.Random.Number(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 ?? _updateArtistTrackRequestFixture.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/Artists/UpdateArtistRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestFixture.cs
new file mode 100644
index 00000000..111a76e0
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestFixture.cs
@@ -0,0 +1,67 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateArtistRequestFixture
+{
+ private readonly Faker _faker = new();
+ private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+
+ ///
+ /// Creates a random valid request to update an artist.
+ ///
+ /// Optional. The name of the artist.
+ /// Optional. The website of the artist.
+ /// Optional. The MusicBrainz identifier of the artist.
+ /// Optional. The media contributors that make up the artist.
+ /// Optional. The albums of the artist.
+ /// Whether the name should be included, or forced to .
+ /// Whether the website should be included, or forced to .
+ /// Whether the MusicBrainz artist Id should be included, or forced to .
+ /// Whether the contributors list should be included, or forced to .
+ /// Whether the albums list should be included, or forced to .
+ /// The created request to update an artist.
+ public UpdateArtistRequest Create(
+ string? name = null,
+ string? website = null,
+ Guid? musicBrainzArtistId = null,
+ List? contributors = null,
+ List? albums = null,
+ bool includeName = true,
+ bool includeWebsite = true,
+ bool includeMusicBrainzArtistId = true,
+ bool includeContributors = true,
+ bool includeAlbums = true)
+ {
+ return new UpdateArtistRequest(
+ includeName ? (name ?? _faker.Name.FullName()) : null,
+ includeWebsite ? (website ?? _faker.Internet.Url()) : null,
+ includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null,
+ includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null,
+ includeAlbums ? (albums ?? _updateArtistAlbumRequestFixture.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/Artists/UpdateArtistTrackRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestFixture.cs
index 82dc2e26..660c83c9 100644
--- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestFixture.cs
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestFixture.cs
@@ -55,7 +55,16 @@ public class UpdateArtistTrackRequestFixture
/// Whether the path should be included, or forced to .
/// Whether the metadata should be included, or forced to .
/// Whether the track number should be included, or forced to .
- /// Whether the optional properties that are not explicitly provided should be randomized, or forced to .
+ /// Whether the disc number should be included, or forced to .
+ /// Whether the script should be included, or forced to .
+ /// Whether the musical key should be included, or forced to .
+ /// Whether the tempo should be included, or forced to .
+ /// Whether the work should be included, or forced to .
+ /// Whether the MusicBrainz recording Id should be included, or forced to .
+ /// Whether the MusicBrainz track Id should be included, or forced to .
+ /// Whether the MusicBrainz work Id should be included, or forced to .
+ /// Whether the moods should be included, or forced to .
+ /// Whether the ISRC codes 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 .
/// The created request to update a track of an album of an artist.
@@ -80,7 +89,16 @@ public class UpdateArtistTrackRequestFixture
bool includePath = true,
bool includeMetadata = true,
bool includeTrackNumber = true,
- bool includeOptionalProperties = true,
+ bool includeDiscNumber = true,
+ bool includeScript = true,
+ bool includeKey = true,
+ bool includeBpm = true,
+ bool includeWork = true,
+ bool includeMusicBrainzRecordingId = true,
+ bool includeMusicBrainzTrackId = true,
+ bool includeMusicBrainzWorkId = true,
+ bool includeMoods = true,
+ bool includeIsrcs = true,
bool includeContributors = true,
bool includeRatings = true)
{
@@ -89,16 +107,16 @@ public class UpdateArtistTrackRequestFixture
includePath ? (path ?? Path.Combine(Path.GetTempPath(), "lumina-tracks", _faker.System.FileName())) : null,
includeMetadata ? (metadata ?? _audioMetadataDtoFixture.Create()) : null,
includeTrackNumber ? (trackNumber ?? _faker.Random.Int(1, 30)) : null,
- includeOptionalProperties ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
- includeOptionalProperties ? (script ?? _faker.Random.AlphaNumeric(4)) : null,
- includeOptionalProperties ? (key ?? _faker.PickRandom()) : null,
- includeOptionalProperties ? (bpm ?? _faker.Random.Int(40, 220)) : null,
- includeOptionalProperties ? (work ?? _faker.Lorem.Sentence()) : null,
- includeOptionalProperties ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null,
- includeOptionalProperties ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null,
- includeOptionalProperties ? (musicBrainzWorkId ?? _faker.Random.Guid()) : null,
- includeOptionalProperties ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
- includeOptionalProperties ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
+ includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null,
+ includeScript ? (script ?? _faker.Random.AlphaNumeric(4)) : null,
+ includeKey ? (key ?? _faker.PickRandom()) : null,
+ includeBpm ? (bpm ?? _faker.Random.Int(40, 220)) : null,
+ includeWork ? (work ?? _faker.Lorem.Sentence()) : null,
+ includeMusicBrainzRecordingId ? (musicBrainzRecordingId ?? _faker.Random.Guid()) : null,
+ includeMusicBrainzTrackId ? (musicBrainzTrackId ?? _faker.Random.Guid()) : null,
+ includeMusicBrainzWorkId ? (musicBrainzWorkId ?? _faker.Random.Guid()) : null,
+ includeMoods ? (moods ?? [.. _moodDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
+ includeIsrcs ? (isrcs ?? [.. _isrcDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null,
includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null);
}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteResponseFixture.cs
new file mode 100644
index 00000000..5bbde1f8
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteResponseFixture.cs
@@ -0,0 +1,44 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ArtistLiteResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the artist.
+ /// Optional. The name of the artist.
+ /// The created .
+ public ArtistLiteResponse Create(
+ Guid? id = null,
+ string? name = null)
+ {
+ return new ArtistLiteResponse(
+ id ?? Guid.NewGuid(),
+ name ?? _faker.Name.FullName());
+ }
+
+ ///
+ /// 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/Artists/ArtistResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponseFixture.cs
new file mode 100644
index 00000000..c8e4178b
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponseFixture.cs
@@ -0,0 +1,81 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
+using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ArtistResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
+ private readonly AlbumResponseFixture _albumResponseFixture = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the artist.
+ /// Optional. The Id of the media library the artist belongs to.
+ /// Optional. The name of the artist.
+ /// Optional. The website of the artist.
+ /// Optional. The MusicBrainz identifier of the artist.
+ /// Optional. The list of contributor references of the artist.
+ /// Optional. The list of albums of the artist.
+ /// Optional. The date and time when the artist was created.
+ /// Optional. The date and time when the artist was updated.
+ /// Whether the website should be included, or forced to .
+ /// Whether the MusicBrainz 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 albums should be included, or forced to .
+ /// The created .
+ public ArtistResponse Create(
+ Guid? id = null,
+ Guid? libraryId = null,
+ string? name = null,
+ string? website = null,
+ Guid? musicBrainzArtistId = null,
+ List? contributors = null,
+ List? albums = null,
+ DateTime? createdOnUtc = null,
+ DateTime? updatedOnUtc = null,
+ bool includeWebsite = true,
+ bool includeMusicBrainzArtistId = true,
+ bool includeUpdatedOnUtc = true,
+ bool includeContributors = true,
+ bool includeAlbums = true)
+ {
+ return new ArtistResponse(
+ id ?? Guid.NewGuid(),
+ libraryId ?? Guid.NewGuid(),
+ name ?? _faker.Name.FullName(),
+ includeWebsite ? (website ?? _faker.Internet.Url()) : null,
+ includeMusicBrainzArtistId ? (musicBrainzArtistId ?? Guid.NewGuid()) : null,
+ includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1)) : null,
+ includeAlbums ? (albums ?? _albumResponseFixture.CreateMany(1)) : null,
+ createdOnUtc ?? _faker.Date.Past().ToUniversalTime(),
+ includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent().ToUniversalTime()) : 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/ArtistRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs
new file mode 100644
index 00000000..3aae0a38
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs
@@ -0,0 +1,1305 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DTO.Filtering;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Common.Infrastructure.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.Filtering;
+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 Microsoft.EntityFrameworkCore.Diagnostics;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Data.Common;
+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 ArtistRepositoryTests
+{
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly TrackEntityFixture _trackEntityFixture = new();
+ private readonly ArtistContributorEntityFixture _artistContributorEntityFixture = 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 PaginationDataDtoFixture _paginationDataDtoFixture = new();
+ private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new();
+
+ [Fact]
+ public async Task InsertAsync_WhenCalledWithAValidArtist_ShouldPersistTheArtistAndItsAggregate()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ artist.Contributors =
+ [_artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ album.Tags = [_tagEntityFixture.Create(name: "InsertAlbumTag")];
+ album.Genres = [_genreEntityFixture.Create(name: "InsertAlbumGenre")];
+ album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)];
+ album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)];
+ TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false);
+ track.Tags = [_tagEntityFixture.Create(name: "InsertTrackTag")];
+ track.Genres = [_genreEntityFixture.Create(name: "InsertTrackGenre")];
+ track.Moods = [_trackMoodEntityFixture.Create(name: "Calm")];
+ track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")];
+ track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)];
+ track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
+ album.Tracks = [track];
+ artist.Albums = [album];
+
+ // Act
+ Result result = await sut.InsertAsync(artist, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(Result.Created, result.Value);
+ ArtistEntity? storedArtist = await context.Artists
+ .AsNoTracking()
+ .Include(candidate => candidate.Contributors)
+ .Include(candidate => candidate.Albums)
+ .ThenInclude(candidate => candidate.Ratings)
+ .Include(candidate => candidate.Albums)
+ .ThenInclude(candidate => candidate.Tags)
+ .Include(candidate => candidate.Albums)
+ .ThenInclude(candidate => candidate.Genres)
+ .Include(candidate => candidate.Albums)
+ .ThenInclude(candidate => candidate.Contributors)
+ .Include(candidate => candidate.Albums)
+ .ThenInclude(candidate => candidate.Tracks)
+ .ThenInclude(candidate => candidate.Tags)
+ .Include(candidate => candidate.Albums)
+ .ThenInclude(candidate => candidate.Tracks)
+ .ThenInclude(candidate => candidate.Genres)
+ .Include(candidate => candidate.Albums)
+ .ThenInclude(candidate => candidate.Tracks)
+ .ThenInclude(candidate => candidate.Moods)
+ .Include(candidate => candidate.Albums)
+ .ThenInclude(candidate => candidate.Tracks)
+ .ThenInclude(candidate => candidate.Isrcs)
+ .AsSplitQuery()
+ .FirstOrDefaultAsync(candidate => candidate.Id == artist.Id);
+ Assert.NotNull(storedArtist);
+ Assert.Single(storedArtist!.Contributors);
+ AlbumEntity storedAlbum = Assert.Single(storedArtist.Albums);
+ Assert.Single(storedAlbum.Ratings);
+ Assert.Single(storedAlbum.Tags);
+ Assert.Single(storedAlbum.Genres);
+ Assert.Single(storedAlbum.Contributors);
+ TrackEntity storedTrack = Assert.Single(storedAlbum.Tracks);
+ Assert.Equal("/music/queen/bohemian-rhapsody.flac", storedTrack.Path);
+ Assert.Single(storedTrack.Tags);
+ Assert.Single(storedTrack.Genres);
+ Assert.Single(storedTrack.Moods);
+ Assert.Single(storedTrack.Isrcs);
+ // Each tag and genre referenced by the aggregate is stored exactly once.
+ Assert.Single(await context.Set().Where(tag => tag.Name == "InsertAlbumTag").ToListAsync());
+ Assert.Single(await context.Set().Where(tag => tag.Name == "InsertTrackTag").ToListAsync());
+ Assert.Single(await context.Set().Where(genre => genre.Name == "InsertAlbumGenre").ToListAsync());
+ Assert.Single(await context.Set().Where(genre => genre.Name == "InsertTrackGenre").ToListAsync());
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenArtistWithTheSameIdAlreadyExists_ShouldReturnArtistAlreadyExists()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-id-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ ArtistEntity existingArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
+ context.Artists.Add(existingArtist);
+ await context.SaveChangesAsync();
+
+ ArtistEntity artist = _artistEntityFixture.Create(id: existingArtist.Id, includeAlbums: false, includeContributors: false);
+
+ // Act
+ Result result = await sut.InsertAsync(artist, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.ArtistAlreadyExists, result.FirstError);
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenAnotherArtistOfTheSameLibraryHasTheSameName_ShouldReturnArtistAlreadyExists()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-name-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
+ context.Artists.Add(existingArtist);
+ await context.SaveChangesAsync();
+
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
+
+ // Act
+ Result result = await sut.InsertAsync(artist, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.ArtistAlreadyExists, result.FirstError);
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenAnotherLibraryHasAnArtistWithTheSameName_ShouldPersistTheArtist()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-otherlibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: Guid.NewGuid(), name: "Queen", includeAlbums: false, includeContributors: false);
+ context.Artists.Add(existingArtist);
+ await context.SaveChangesAsync();
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false);
+
+ // Act
+ Result result = await sut.InsertAsync(artist, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(Result.Created, result.Value);
+ ArtistEntity? storedArtist = await context.Artists.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == artist.Id);
+ Assert.NotNull(storedArtist);
+ Assert.Equal(libraryId, storedArtist!.LibraryId);
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenTwoTracksOfTheSameRequestShareAPath_ShouldReturnTrackAlreadyExists()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-duprequest-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false);
+ album.Tracks =
+ [
+ _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false),
+ _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false)
+ ];
+ artist.Albums = [album];
+
+ // Act
+ Result result = await sut.InsertAsync(artist, 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-artistrepo-insert-storedpath-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity existingArtist = await SeedArtistAsync(context, libraryId, "Existing");
+ AlbumEntity existingAlbum = await SeedAlbumAsync(context, libraryId, existingArtist.Id);
+ context.Tracks.Add(_trackEntityFixture.Create(
+ albumId: existingAlbum.Id, libraryId: libraryId, path: "/music/queen/we-will-rock-you.flac", includeMetadata: false));
+ await context.SaveChangesAsync();
+
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ 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/we-will-rock-you.flac", includeMetadata: false)];
+ artist.Albums = [album];
+
+ // Act
+ Result result = await sut.InsertAsync(artist, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldPersistTheArtist()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-otherlibrarypath-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid firstLibraryId = Guid.NewGuid();
+ ArtistEntity firstArtist = await SeedArtistAsync(context, firstLibraryId, "First");
+ AlbumEntity firstAlbum = await SeedAlbumAsync(context, firstLibraryId, firstArtist.Id);
+ 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 artist = _artistEntityFixture.Create(libraryId: secondLibraryId, includeAlbums: false, includeContributors: false);
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.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)];
+ artist.Albums = [album];
+
+ // Act
+ Result result = await sut.InsertAsync(artist, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(Result.Created, result.Value);
+ ArtistEntity? storedArtist = await context.Artists.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == artist.Id);
+ Assert.NotNull(storedArtist);
+ Assert.Equal(secondLibraryId, storedArtist!.LibraryId);
+ }
+
+ [Fact]
+ public async Task InsertAsync_WhenTagsAndGenresAlreadyExistByName_ShouldReuseTheStoredRows()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-reuse-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ context.Set().Add(_tagEntityFixture.Create(name: "ExistingTag"));
+ context.Set().Add(_genreEntityFixture.Create(name: "ExistingGenre"));
+ await context.SaveChangesAsync();
+
+ ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.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: artist.LibraryId, includeMetadata: false);
+ track.Tags = [_tagEntityFixture.Create(name: "ExistingTag")];
+ track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")];
+ album.Tracks = [track];
+ artist.Albums = [album];
+
+ // Act
+ Result result = await sut.InsertAsync(artist, 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-artistrepo-insert-shared-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false);
+ TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.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];
+ artist.Albums = [album];
+
+ // Act
+ Result result = await sut.InsertAsync(artist, 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_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTrack_ShouldPersistItOnce()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-shared-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ AlbumEntity 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 = [];
+ album.Genres = [];
+ track.Tags = [];
+ track.Genres = [];
+ album.Tracks = [track];
+ artist.Albums = [album];
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+
+ ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id);
+ AlbumEntity incomingAlbum = Assert.Single(incoming.Albums);
+ TrackEntity incomingTrack = Assert.Single(incomingAlbum.Tracks);
+ incomingAlbum.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")];
+ incomingAlbum.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")];
+ incomingTrack.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")];
+ incomingTrack.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")];
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(Result.Updated, result.Value);
+ // The name shared by the album and its track 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-artistrepo-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);
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ artist.Contributors =
+ [_artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ album.Tags = [_tagEntityFixture.Create(name: "NoopAlbumTag")];
+ album.Genres = [_genreEntityFixture.Create(name: "NoopAlbumGenre")];
+ TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
+ track.Tags = [_tagEntityFixture.Create(name: "NoopTrackTag")];
+ track.Genres = [_genreEntityFixture.Create(name: "NoopTrackGenre")];
+ album.Tracks = [track];
+ artist.Albums = [album];
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+ Guid contributorId = artist.Contributors[0].Id;
+ DateTime contributorCreatedOnUtc = artist.Contributors[0].CreatedOnUtc;
+ ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id);
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ArtistEntity? storedArtist = await context.Artists
+ .AsNoTracking()
+ .Include(candidate => candidate.Contributors)
+ .Include(candidate => candidate.Albums)
+ .ThenInclude(candidate => candidate.Tracks)
+ .AsSplitQuery()
+ .FirstOrDefaultAsync(candidate => candidate.Id == artist.Id);
+ Assert.NotNull(storedArtist);
+ Assert.Null(storedArtist!.UpdatedOnUtc);
+ ArtistContributorEntity storedContributor = Assert.Single(storedArtist.Contributors);
+ Assert.Equal(contributorId, storedContributor.Id);
+ Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
+ // The tag and genre rows of the album and its track are left untouched.
+ Assert.Single(await context.Set().Where(tag => tag.Name == "NoopAlbumTag").ToListAsync());
+ Assert.Single(await context.Set().Where(tag => tag.Name == "NoopTrackTag").ToListAsync());
+ Assert.Single(await context.Set().Where(genre => genre.Name == "NoopAlbumGenre").ToListAsync());
+ Assert.Single(await context.Set().Where(genre => genre.Name == "NoopTrackGenre").ToListAsync());
+ }
+
+ [Fact]
+ public async Task UpdateAsync_WhenOnlyTheScalarValuesChanged_ShouldStampTheArtistAndKeepChildIdentity()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-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);
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ artist.Contributors =
+ [_artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+ Guid contributorId = artist.Contributors[0].Id;
+ DateTime contributorCreatedOnUtc = artist.Contributors[0].CreatedOnUtc;
+ ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id);
+ incoming.Name = "Freddie Mercury";
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ArtistEntity? storedArtist = await context.Artists.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == artist.Id);
+ Assert.NotNull(storedArtist);
+ Assert.Equal("Freddie Mercury", storedArtist!.Name);
+ // Only the edited artist is stamped, the child rows keep their identity and their audit columns.
+ Assert.Equal(utcNow, storedArtist.UpdatedOnUtc);
+ Assert.Equal(userId, storedArtist.UpdatedBy);
+ ArtistContributorEntity storedContributor = Assert.Single(storedArtist.Contributors);
+ Assert.Equal(contributorId, storedContributor.Id);
+ Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc);
+ }
+
+ [Fact]
+ public async Task UpdateAsync_WhenAContributorIsRemoved_ShouldDeleteOnlyThatParticipationAndKeepTheOtherIdentity()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-removecontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid keptMediaContributorId = Guid.NewGuid();
+ ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
+ ArtistContributorEntity keptContributor = _artistContributorEntityFixture.Create(
+ artistId: artist.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer);
+ ArtistContributorEntity removedContributor = _artistContributorEntityFixture.Create(
+ artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Composer);
+ artist.Contributors = [keptContributor, removedContributor];
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+ Guid keptContributorId = keptContributor.Id;
+ ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id);
+ incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId)];
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ List storedContributors = await context.Set()
+ .AsNoTracking()
+ .Where(contributor => contributor.ArtistId == artist.Id)
+ .ToListAsync();
+ ArtistContributorEntity storedContributor = Assert.Single(storedContributors);
+ Assert.Equal(keptContributorId, storedContributor.Id);
+ Assert.Equal(keptMediaContributorId, storedContributor.MediaContributorId);
+ }
+
+ [Fact]
+ public async Task UpdateAsync_WhenAnAlbumAndItsTrackAreAdded_ShouldPersistThem()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-addalbum-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id);
+ AlbumEntity addedAlbum = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ addedAlbum.Tracks =
+ [_trackEntityFixture.Create(albumId: addedAlbum.Id, libraryId: libraryId, path: "/music/queen/love-of-my-life.flac", includeMetadata: false)];
+ incoming.Albums = [addedAlbum];
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().Include(album => album.Tracks).FirstOrDefaultAsync(album => album.Id == addedAlbum.Id);
+ Assert.NotNull(storedAlbum);
+ TrackEntity storedTrack = Assert.Single(storedAlbum!.Tracks);
+ Assert.Equal("/music/queen/love-of-my-life.flac", storedTrack.Path);
+ }
+
+ [Fact]
+ public async Task UpdateAsync_WhenANewTrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-dup-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id);
+ context.Tracks.Add(_trackEntityFixture.Create(
+ albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false));
+ await context.SaveChangesAsync();
+
+ ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id);
+ AlbumEntity incomingAlbum = incoming.Albums.Single();
+ TrackEntity addedTrack = _trackEntityFixture.Create(
+ albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false);
+ incomingAlbum.Tracks.Add(addedTrack);
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError);
+ Assert.Equal(1, await context.Tracks.CountAsync(candidate => candidate.LibraryId == libraryId));
+ }
+
+ [Fact]
+ public async Task DeleteByIdAsync_WhenArtistExists_ShouldDeleteTheArtistAndItsChildren()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-delete-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id);
+ context.Tracks.Add(_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false));
+ await context.SaveChangesAsync();
+
+ // Act
+ Result result = await sut.DeleteByIdAsync(artist.Id, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(Result.Deleted, result.Value);
+ Assert.Null(await context.Artists.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == artist.Id));
+ Assert.Empty(await context.Albums.AsNoTracking().Where(candidate => candidate.ArtistId == artist.Id).ToListAsync());
+ Assert.Empty(await context.Tracks.AsNoTracking().Where(candidate => candidate.LibraryId == libraryId).ToListAsync());
+ }
+
+ [Fact]
+ public async Task GetByIdAsync_WhenArtistExists_ShouldIncludeTheNavigationProperties()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getbyid-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedFullArtistAsync(context, libraryId);
+
+ // Act
+ Result result = await sut.GetByIdAsync(artist.Id, cancellationToken: CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ArtistEntity retrievedArtist = result.Value!;
+ Assert.Single(retrievedArtist.Contributors);
+ AlbumEntity retrievedAlbum = Assert.Single(retrievedArtist.Albums);
+ 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_ShouldReturnAnUntrackedArtist()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getbyid-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ context.ChangeTracker.Clear();
+
+ // Act
+ Result result = await sut.GetByIdAsync(
+ artist.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 GetAllAsync_WhenCalled_ShouldReturnOnlyTheLibraryArtistsWithPagination()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getall-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ List artists = _artistEntityFixture.CreateMany(3);
+ foreach (ArtistEntity artist in artists)
+ {
+ artist.LibraryId = libraryId;
+ artist.Albums = [];
+ artist.Contributors = [];
+ }
+ ArtistEntity artistOfAnotherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false);
+ context.Artists.AddRange(artists);
+ context.Artists.Add(artistOfAnotherLibrary);
+ await context.SaveChangesAsync();
+
+ PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
+ LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
+
+ // Act
+ Result> result = await sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(3, result.Value.Count);
+ Assert.Equal(3, result.Value.Data.Count);
+ Assert.DoesNotContain(result.Value.Data, artist => artist.Id == artistOfAnotherLibrary.Id);
+ }
+
+ [Fact]
+ public async Task GetAllAsync_WhenTheSearchTermDiffersInCase_ShouldMatchCaseInsensitively()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getall-search-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity matchingArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false);
+ ArtistEntity otherArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Radiohead", includeAlbums: false, includeContributors: false);
+ context.Artists.AddRange(matchingArtist, otherArtist);
+ await context.SaveChangesAsync();
+
+ LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "QUEENS");
+
+ // Act
+ Result> result = await sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ArtistEntity retrievedArtist = Assert.Single(result.Value.Data);
+ Assert.Equal(matchingArtist.Id, retrievedArtist.Id);
+ }
+
+ [Fact]
+ public async Task GetAllAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnUntrackedArtists()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getall-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+ context.ChangeTracker.Clear();
+ LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
+
+ // Act
+ Result> result = await sut.GetAllAsync(
+ null, null, null, filter, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Single(result.Value.Data);
+ Assert.Empty(context.ChangeTracker.Entries());
+ }
+
+ [Fact]
+ public async Task GetAllLiteAsync_WhenPaginationDataIsNull_ShouldReturnTheArtistLiteRowsOrdered()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-lite-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false);
+ ArtistEntity alphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false);
+ context.Artists.AddRange(betaArtist, alphaArtist);
+ await context.SaveChangesAsync();
+
+ LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
+
+ // Act
+ Result> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal([alphaArtist.Id, betaArtist.Id], result.Value.Data.Select(row => row.Id));
+ Assert.Equal([alphaArtist.Name, betaArtist.Name], result.Value.Data.Select(row => row.Name));
+ Assert.Equal(2, result.Value.Count);
+ Assert.Equal(1, result.Value.CurrentPage);
+ Assert.Equal(2, result.Value.PerPage);
+ }
+
+ [Fact]
+ public async Task GetAllLiteAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnUntrackedRows()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getalllite-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+ context.ChangeTracker.Clear();
+ LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
+
+ // Act
+ Result> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Single(result.Value.Data);
+ Assert.Empty(context.ChangeTracker.Entries());
+ }
+
+ [Fact]
+ public async Task UpdateAsync_WhenManyTracksAreUpdated_ShouldNotReloadEachTrackIndividually()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-queries-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ SelectCountingInterceptor interceptor = new();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder()
+ .UseSqlite(anchorConnection.ConnectionString)
+ .AddInterceptors(interceptor)
+ .Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid smallLibraryId = Guid.NewGuid();
+ ArtistEntity smallArtist = SeedArtistWithAlbums(context, smallLibraryId, albumCount: 1, tracksPerAlbum: 1);
+ await context.SaveChangesAsync();
+
+ Guid largeLibraryId = Guid.NewGuid();
+ ArtistEntity largeArtist = SeedArtistWithAlbums(context, largeLibraryId, albumCount: 4, tracksPerAlbum: 10);
+ await context.SaveChangesAsync();
+
+ ArtistEntity smallIncoming = await LoadDetachedArtistAsync(context, smallArtist.Id);
+ ArtistEntity largeIncoming = await LoadDetachedArtistAsync(context, largeArtist.Id);
+
+ // Act
+ interceptor.Reset();
+ Result smallResult = await sut.UpdateAsync(smallIncoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+ int smallSelectCount = interceptor.SelectCount;
+
+ interceptor.Reset();
+ Result largeResult = await sut.UpdateAsync(largeIncoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+ int largeSelectCount = interceptor.SelectCount;
+
+ // Assert
+ Assert.False(smallResult.IsFailure);
+ Assert.False(largeResult.IsFailure);
+ // The artist aggregate is loaded once and the children are applied to the already tracked instances, so the number of read queries
+ // does not grow with the number of albums or tracks of the aggregate.
+ Assert.True(largeSelectCount <= smallSelectCount + 2, $"The large aggregate issued {largeSelectCount} read queries, while the small aggregate issued {smallSelectCount}.");
+ }
+
+ [Fact]
+ public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateAnyReconciledChildCollection()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-noop-collections-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ artist.Contributors =
+ [
+ _artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals),
+ _artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)
+ ];
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ album.Tags = [_tagEntityFixture.Create(name: $"noop-album-tag-{Guid.NewGuid():N}"), _tagEntityFixture.Create(name: $"noop-album-tag-two-{Guid.NewGuid():N}")];
+ album.Genres = [_genreEntityFixture.Create(name: $"noop-album-genre-{Guid.NewGuid():N}"), _genreEntityFixture.Create(name: $"noop-album-genre-two-{Guid.NewGuid():N}")];
+ album.Ratings =
+ [
+ _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
+ _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)
+ ];
+ album.Contributors =
+ [
+ _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer),
+ _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Composer)
+ ];
+ TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
+ track.Tags = [_tagEntityFixture.Create(name: $"noop-track-tag-{Guid.NewGuid():N}"), _tagEntityFixture.Create(name: $"noop-track-tag-two-{Guid.NewGuid():N}")];
+ track.Genres = [_genreEntityFixture.Create(name: $"noop-track-genre-{Guid.NewGuid():N}"), _genreEntityFixture.Create(name: $"noop-track-genre-two-{Guid.NewGuid():N}")];
+ track.Ratings =
+ [
+ _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
+ _audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.User, voteCount: 20)
+ ];
+ 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),
+ _trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)
+ ];
+ album.Tracks = [track];
+ artist.Albums = [album];
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+ // Detach the seeded graph, so that the update must load the tracked aggregate through its include chain instead of returning the already populated seeded instances.
+ context.ChangeTracker.Clear();
+
+ ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id);
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ArtistEntity? storedArtist = await context.Artists.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == artist.Id);
+ Assert.NotNull(storedArtist);
+ Assert.Equal(2, storedArtist!.Contributors.Count);
+ AlbumEntity? storedAlbum = await context.Albums
+ .AsNoTracking()
+ .Include(candidate => candidate.Tags)
+ .Include(candidate => candidate.Genres)
+ .Include(candidate => candidate.Ratings)
+ .Include(candidate => candidate.Contributors)
+ .FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
+ Assert.NotNull(storedAlbum);
+ Assert.Equal(2, storedAlbum!.Tags.Count);
+ Assert.Equal(2, storedAlbum.Genres.Count);
+ Assert.Equal(2, storedAlbum.Ratings.Count);
+ Assert.Equal(2, storedAlbum.Contributors.Count);
+ TrackEntity? storedTrack = await context.Tracks
+ .AsNoTracking()
+ .Include(candidate => candidate.Tags)
+ .Include(candidate => candidate.Genres)
+ .Include(candidate => candidate.Ratings)
+ .Include(candidate => candidate.Moods)
+ .Include(candidate => candidate.Isrcs)
+ .Include(candidate => candidate.Contributors)
+ .FirstOrDefaultAsync(candidate => candidate.Id == track.Id);
+ Assert.NotNull(storedTrack);
+ Assert.Equal(2, storedTrack!.Tags.Count);
+ Assert.Equal(2, storedTrack.Genres.Count);
+ Assert.Equal(2, storedTrack.Ratings.Count);
+ Assert.Equal(2, storedTrack.Moods.Count);
+ Assert.Equal(2, storedTrack.Isrcs.Count);
+ Assert.Equal(2, storedTrack.Contributors.Count);
+ }
+
+ [Fact]
+ public async Task UpdateAsync_WhenOneItemIsRemovedFromEachReconciledChildCollection_ShouldRemoveOnlyThoseItems()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-remove-collections-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options);
+ context.Database.EnsureCreated();
+ ArtistRepository sut = CreateArtistRepository(context);
+
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ ArtistContributorEntity keptArtistContributor = _artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals);
+ artist.Contributors = [keptArtistContributor, _artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)];
+
+ string keptAlbumTagName = $"remove-album-tag-{Guid.NewGuid():N}";
+ string keptAlbumGenreName = $"remove-album-genre-{Guid.NewGuid():N}";
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ album.Tags = [_tagEntityFixture.Create(name: keptAlbumTagName), _tagEntityFixture.Create(name: $"remove-album-tag-two-{Guid.NewGuid():N}")];
+ album.Genres = [_genreEntityFixture.Create(name: keptAlbumGenreName), _genreEntityFixture.Create(name: $"remove-album-genre-two-{Guid.NewGuid():N}")];
+ album.Ratings =
+ [
+ _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
+ _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)
+ ];
+ AlbumContributorEntity keptAlbumContributor = _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer);
+ album.Contributors = [keptAlbumContributor, _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Composer)];
+
+ string keptTrackTagName = $"remove-track-tag-{Guid.NewGuid():N}";
+ string keptTrackGenreName = $"remove-track-genre-{Guid.NewGuid():N}";
+ TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false);
+ track.Tags = [_tagEntityFixture.Create(name: keptTrackTagName), _tagEntityFixture.Create(name: $"remove-track-tag-two-{Guid.NewGuid():N}")];
+ track.Genres = [_genreEntityFixture.Create(name: keptTrackGenreName), _genreEntityFixture.Create(name: $"remove-track-genre-two-{Guid.NewGuid():N}")];
+ track.Ratings =
+ [
+ _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100),
+ _audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.User, voteCount: 20)
+ ];
+ track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")];
+ track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")];
+ TrackContributorEntity keptTrackContributor = _trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals);
+ track.Contributors = [keptTrackContributor, _trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)];
+ album.Tracks = [track];
+ artist.Albums = [album];
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+ // Detach the seeded graph, so that the update must load the tracked aggregate through its include chain instead of returning the already populated seeded instances.
+ context.ChangeTracker.Clear();
+
+ ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id);
+ AlbumEntity incomingAlbum = Assert.Single(incoming.Albums);
+ TrackEntity incomingTrack = Assert.Single(incomingAlbum.Tracks);
+ incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.Id == keptArtistContributor.Id)];
+ incomingAlbum.Tags = [incomingAlbum.Tags.Single(tag => tag.Name == keptAlbumTagName)];
+ incomingAlbum.Genres = [incomingAlbum.Genres.Single(genre => genre.Name == keptAlbumGenreName)];
+ incomingAlbum.Ratings = [incomingAlbum.Ratings.Single(rating => rating.Source == AudioRatingSource.MusicBrainz)];
+ incomingAlbum.Contributors = [incomingAlbum.Contributors.Single(contributor => contributor.Id == keptAlbumContributor.Id)];
+ incomingTrack.Tags = [incomingTrack.Tags.Single(tag => tag.Name == keptTrackTagName)];
+ incomingTrack.Genres = [incomingTrack.Genres.Single(genre => genre.Name == keptTrackGenreName)];
+ incomingTrack.Ratings = [incomingTrack.Ratings.Single(rating => rating.Source == AudioRatingSource.MusicBrainz)];
+ incomingTrack.Moods = [incomingTrack.Moods.Single(mood => mood.Name == "Calm")];
+ incomingTrack.Isrcs = [incomingTrack.Isrcs.Single(isrc => isrc.Value == "USRC12345678")];
+ incomingTrack.Contributors = [incomingTrack.Contributors.Single(contributor => contributor.Id == keptTrackContributor.Id)];
+
+ // Act
+ Result result = await sut.UpdateAsync(incoming, CancellationToken.None);
+ await context.SaveChangesAsync();
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ArtistEntity? storedArtist = await context.Artists.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == artist.Id);
+ Assert.NotNull(storedArtist);
+ ArtistContributorEntity storedArtistContributor = Assert.Single(storedArtist!.Contributors);
+ Assert.Equal(keptArtistContributor.Id, storedArtistContributor.Id);
+ AlbumEntity? storedAlbum = await context.Albums
+ .AsNoTracking()
+ .Include(candidate => candidate.Tags)
+ .Include(candidate => candidate.Genres)
+ .Include(candidate => candidate.Ratings)
+ .Include(candidate => candidate.Contributors)
+ .FirstOrDefaultAsync(candidate => candidate.Id == album.Id);
+ Assert.NotNull(storedAlbum);
+ Assert.Equal(keptAlbumTagName, Assert.Single(storedAlbum!.Tags).Name);
+ Assert.Equal(keptAlbumGenreName, Assert.Single(storedAlbum.Genres).Name);
+ Assert.Equal(AudioRatingSource.MusicBrainz, Assert.Single(storedAlbum.Ratings).Source);
+ Assert.Equal(keptAlbumContributor.Id, Assert.Single(storedAlbum.Contributors).Id);
+ TrackEntity? storedTrack = await context.Tracks
+ .AsNoTracking()
+ .Include(candidate => candidate.Tags)
+ .Include(candidate => candidate.Genres)
+ .Include(candidate => candidate.Ratings)
+ .Include(candidate => candidate.Moods)
+ .Include(candidate => candidate.Isrcs)
+ .Include(candidate => candidate.Contributors)
+ .FirstOrDefaultAsync(candidate => candidate.Id == track.Id);
+ Assert.NotNull(storedTrack);
+ Assert.Equal(keptTrackTagName, Assert.Single(storedTrack!.Tags).Name);
+ Assert.Equal(keptTrackGenreName, Assert.Single(storedTrack.Genres).Name);
+ Assert.Equal(AudioRatingSource.MusicBrainz, Assert.Single(storedTrack.Ratings).Source);
+ Assert.Equal("Calm", Assert.Single(storedTrack.Moods).Name);
+ Assert.Equal("USRC12345678", Assert.Single(storedTrack.Isrcs).Value);
+ Assert.Equal(keptTrackContributor.Id, Assert.Single(storedTrack.Contributors).Id);
+ }
+
+ ///
+ /// Seeds an artist that owns the requested number of albums, each with the requested number of tracks, all of them with distinct shared reference names.
+ ///
+ /// The context the artist is persisted through.
+ /// The Id of the library that owns the artist.
+ /// The number of albums the artist owns.
+ /// The number of tracks each album owns.
+ /// The created artist.
+ private ArtistEntity SeedArtistWithAlbums(LuminaDbContext context, Guid libraryId, int albumCount, int tracksPerAlbum)
+ {
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ List albums = [];
+ for (int albumIndex = 0; albumIndex < albumCount; albumIndex++)
+ {
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ album.Tags = [_tagEntityFixture.Create(name: $"album-tag-{libraryId:N}-{albumIndex}")];
+ album.Genres = [_genreEntityFixture.Create(name: $"album-genre-{libraryId:N}-{albumIndex}")];
+ List tracks = [];
+ for (int trackIndex = 0; trackIndex < tracksPerAlbum; trackIndex++)
+ {
+ TrackEntity track = _trackEntityFixture.Create(
+ albumId: album.Id, libraryId: libraryId, path: $"/music/{libraryId:N}/track-{albumIndex}-{trackIndex}.flac", includeMetadata: false);
+ track.Tags = [_tagEntityFixture.Create(name: $"track-tag-{libraryId:N}-{albumIndex}-{trackIndex}")];
+ track.Genres = [_genreEntityFixture.Create(name: $"track-genre-{libraryId:N}-{albumIndex}-{trackIndex}")];
+ tracks.Add(track);
+ }
+ album.Tracks = tracks;
+ albums.Add(album);
+ }
+ artist.Albums = albums;
+ context.Artists.Add(artist);
+ return artist;
+ }
+
+ ///
+ /// Creates an artist repository backed by the provided context, wiring the real album and track repositories.
+ ///
+ /// The context the repository operates on.
+ /// The created repository.
+ private static ArtistRepository CreateArtistRepository(LuminaDbContext context)
+ {
+ TrackRepository trackRepository = new(context);
+ AlbumRepository albumRepository = new(context, trackRepository);
+ return new ArtistRepository(context, albumRepository, trackRepository);
+ }
+
+ ///
+ /// Seeds an artist with no albums or contributors.
+ ///
+ /// The context the artist is persisted through.
+ /// The Id of the library that owns the artist.
+ /// The name of the artist.
+ /// The persisted artist.
+ private async Task SeedArtistAsync(LuminaDbContext context, Guid libraryId, string name)
+ {
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false);
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+ return artist;
+ }
+
+ ///
+ /// Seeds an artist with one album and one track, including every related collection deterministically.
+ ///
+ /// The context the artist is persisted through.
+ /// The Id of the library that owns the artist.
+ /// The persisted artist.
+ private async Task SeedFullArtistAsync(LuminaDbContext context, Guid libraryId)
+ {
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
+ artist.Contributors =
+ [_artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)];
+ 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)];
+ 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];
+ artist.Albums = [album];
+ 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 persisted album.
+ private async Task SeedAlbumAsync(LuminaDbContext context, Guid libraryId, Guid artistId)
+ {
+ AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: false);
+ context.Albums.Add(album);
+ await context.SaveChangesAsync();
+ return album;
+ }
+
+ ///
+ /// Loads a detached copy of a stored artist 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 artist.
+ /// The Id of the artist to load.
+ /// The detached copy of the artist.
+ private static async Task LoadDetachedArtistAsync(LuminaDbContext context, Guid artistId)
+ {
+ return await context.Artists
+ .AsNoTracking()
+ .Include(artist => artist.Contributors)
+ .Include(artist => artist.Albums)
+ .ThenInclude(album => album.Ratings)
+ .Include(artist => artist.Albums)
+ .ThenInclude(album => album.Tags)
+ .Include(artist => artist.Albums)
+ .ThenInclude(album => album.Genres)
+ .Include(artist => artist.Albums)
+ .ThenInclude(album => album.Contributors)
+ .Include(artist => artist.Albums)
+ .ThenInclude(album => album.Tracks)
+ .ThenInclude(track => track.Ratings)
+ .Include(artist => artist.Albums)
+ .ThenInclude(album => album.Tracks)
+ .ThenInclude(track => track.Genres)
+ .Include(artist => artist.Albums)
+ .ThenInclude(album => album.Tracks)
+ .ThenInclude(track => track.Tags)
+ .Include(artist => artist.Albums)
+ .ThenInclude(album => album.Tracks)
+ .ThenInclude(track => track.Moods)
+ .Include(artist => artist.Albums)
+ .ThenInclude(album => album.Tracks)
+ .ThenInclude(track => track.Isrcs)
+ .Include(artist => artist.Albums)
+ .ThenInclude(album => album.Tracks)
+ .ThenInclude(track => track.Contributors)
+ .AsSplitQuery()
+ .FirstAsync(artist => artist.Id == artistId);
+ }
+
+ ///
+ /// 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;
+ }
+
+ ///
+ /// Counts the number of read commands issued through a context, so that tests can assert that the number of queries does not scale with the aggregate size.
+ ///
+ private sealed class SelectCountingInterceptor : DbCommandInterceptor
+ {
+ ///
+ /// Gets the number of SELECT commands observed since the last reset.
+ ///
+ public int SelectCount { get; private set; }
+
+ ///
+ /// Resets the observed command count.
+ ///
+ public void Reset()
+ {
+ SelectCount = 0;
+ }
+
+ ///
+ /// Counts the command before it is executed synchronously.
+ ///
+ /// The command that is about to be executed.
+ /// The event data of the command.
+ /// The interception result.
+ /// The interception result, unmodified.
+ public override InterceptionResult ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult result)
+ {
+ CountIfSelect(command);
+ return base.ReaderExecuting(command, eventData, result);
+ }
+
+ ///
+ /// Counts the command before it is executed asynchronously.
+ ///
+ /// The command that is about to be executed.
+ /// The event data of the command.
+ /// The interception result.
+ /// Cancellation token that can be used to stop the execution.
+ /// The interception result, unmodified.
+ public override ValueTask> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
+ {
+ CountIfSelect(command);
+ return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
+ }
+
+ ///
+ /// Increments the count when is a SELECT statement.
+ ///
+ /// The command to inspect.
+ private void CountIfSelect(DbCommand command)
+ {
+ if (command.CommandText.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
+ SelectCount++;
+ }
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs
new file mode 100644
index 00000000..4aa58116
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs
@@ -0,0 +1,349 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+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.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+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.Artists.AddArtist;
+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.Artists.AddArtist;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class AddArtistEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+ private readonly AddArtistRequestFixture _addArtistRequestFixture = new();
+ private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
+ private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public AddArtistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task AddArtist_WhenCalledWithValidData_ShouldAddArtist()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ AddAlbumRequest album = _addAlbumRequestFixture.Create(
+ metadata: _albumMetadataDtoFixture.Create(title: "A Night at the Opera"),
+ contributors: [],
+ ratings: [],
+ tracks: []);
+ AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: [album]);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ ArtistResponse? artistResponse = JsonSerializer.Deserialize(content, _jsonOptions);
+ Assert.NotNull(artistResponse);
+ Assert.Equal(libraryId, artistResponse!.LibraryId);
+ Assert.Equal("Queen", artistResponse.Name);
+ Assert.NotNull(artistResponse.Albums);
+ AlbumResponse albumResponse = Assert.Single(artistResponse.Albums!);
+ Assert.Equal("A Night at the Opera", albumResponse.Metadata.Title);
+
+ Assert.NotNull(response.Headers.Location);
+ Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{artistResponse.Id}", response.Headers.Location!.ToString());
+ }
+
+ [Fact]
+ public async Task AddArtist_WhenNameIsMissing_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ AddArtistRequest request = _addArtistRequestFixture.Create(includeName: false, contributors: [], albums: []);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, $"/api/v1/libraries/{libraryId}/artists", Errors.Music.ArtistNameCannotBeEmpty.Description);
+ }
+
+ [Fact]
+ public async Task AddArtist_WhenAlbumsAreMissing_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], includeAlbums: false);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, $"/api/v1/libraries/{libraryId}/artists", Errors.Music.AlbumsListCannotBeNull.Description);
+ }
+
+ [Fact]
+ public async Task AddArtist_WhenAlbumMetadataIsMissing_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ AddAlbumRequest album = _addAlbumRequestFixture.Create(includeMetadata: false, contributors: [], ratings: [], tracks: []);
+ AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: [album]);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, $"/api/v1/libraries/{libraryId}/artists", Errors.Metadata.MetadataCannotBeNull.Description);
+ }
+
+ [Fact]
+ public async Task AddArtist_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
+ AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: [album]);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{otherLibraryId}/artists", request);
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", $"/api/v1/libraries/{otherLibraryId}/artists", "https://tools.ietf.org/html/rfc9110#section-15.5.4");
+ }
+
+ [Fact]
+ public async Task AddArtist_WhenLibraryDoesNotExist_ShouldReturnNotFound()
+ {
+ // Arrange
+ // only an admin reaches the library lookup of a library that does not exist, because a regular user is rejected by the ownership policy before it
+ HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
+ Guid missingLibraryId = Guid.NewGuid();
+ AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: [album]);
+
+ // Act
+ HttpResponseMessage response = await adminClient.PostAsJsonAsync($"/api/v1/libraries/{missingLibraryId}/artists", request);
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", Errors.Library.LibraryNotFound.Description, $"/api/v1/libraries/{missingLibraryId}/artists", "https://tools.ietf.org/html/rfc9110#section-15.5.5");
+ }
+
+ [Fact]
+ public async Task AddArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: [album]);
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync(url, request);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task AddArtist_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: [album]);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/not-a-guid/artists", request);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, "/api/v1/libraries/not-a-guid/artists", Errors.Library.LibraryIdCannotBeEmpty.Description);
+ }
+
+ [Fact]
+ public async Task AddArtist_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
+ AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: [album]);
+ using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5));
+
+ // Act & Assert
+ Exception? exception = await Record.ExceptionAsync(async () =>
+ await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request, cts.Token));
+ Assert.Null(exception);
+ }
+
+ ///
+ /// Seeds a music library of type music, owned by , whose single content location is the temp path.
+ ///
+ /// 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 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 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"]));
+ }
+
+ ///
+ /// 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());
+ }
+
+ ///
+ /// 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/Artists/DeleteArtist/DeleteArtistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs
new file mode 100644
index 00000000..c9d6ba48
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs
@@ -0,0 +1,311 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist;
+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.Artists.DeleteArtist;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteArtistEndpointTests : 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 UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public DeleteArtistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task DeleteArtist_WhenArtistBelongsToAnOwnedLibrary_ShouldDeleteTheArtist()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Null(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId));
+ }
+
+ [Fact]
+ public async Task DeleteArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task DeleteArtist_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, Guid artistId) = await SeedLibraryAndArtistAsync(userId);
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task DeleteArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}";
+
+ // 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 DeleteArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task DeleteArtist_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task DeleteArtist_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
+ }
+
+ ///
+ /// 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 of that library.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library and artist.
+ private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ 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", includeAlbums: false, includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, 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/Artists/GetArtist/GetArtistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs
new file mode 100644
index 00000000..c28f898a
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs
@@ -0,0 +1,310 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist;
+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.Artists.GetArtist;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistEndpointTests : 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 UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetArtistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task GetArtist_WhenArtistBelongsToAnOwnedLibrary_ShouldReturnArtistDetails()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId, "Queen");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ ArtistResponse? artist = JsonSerializer.Deserialize(content, _jsonOptions);
+ Assert.NotNull(artist);
+ Assert.Equal(artistId, artist!.Id);
+ Assert.Equal(libraryId, artist.LibraryId);
+ Assert.Equal("Queen", artist.Name);
+ }
+
+ [Fact]
+ public async Task GetArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = Guid.NewGuid();
+ using (IServiceScope scope = _apiFactory.Services.CreateScope())
+ {
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ }
+
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetArtist_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, Guid artistId) = await SeedLibraryAndArtistAsync(userId, "Queen");
+ // The route library id is enforced, so an artist of another library is reported as not found, without disclosing that it exists.
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId, "Queen");
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}";
+
+ // 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 GetArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetArtist_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task GetArtist_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist of that library.
+ ///
+ /// The Id of the user that owns the library.
+ /// The name of the seeded artist.
+ /// The Ids of the seeded library and artist.
+ private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId, string artistName)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ 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: artistName, includeAlbums: false, includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, 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/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs
new file mode 100644
index 00000000..42dd615d
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs
@@ -0,0 +1,353 @@
+#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.Artists.GetArtistAlbums;
+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.Artists.GetArtistAlbums;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistAlbumsEndpointTests : 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 GetArtistAlbumsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task GetArtistAlbums_WhenArtistHasAlbums_ShouldReturnAlbumDetails()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid artistId = await SeedArtistAsync(libraryId);
+ await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
+ await SeedAlbumAsync(libraryId, artistId, "News of the World");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? albums = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(albums);
+ Assert.Equal(2, albums!.Count);
+ Assert.Contains(albums, album => album.Metadata.Title == "A Night at the Opera");
+ Assert.Contains(albums, album => album.Metadata.Title == "News of the World");
+ }
+
+ [Fact]
+ public async Task GetArtistAlbums_WhenArtistHasNoAlbums_ShouldReturnEmptyCollection()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid artistId = await SeedArtistAsync(libraryId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? albums = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(albums);
+ Assert.Empty(albums!);
+ }
+
+ [Fact]
+ public async Task GetArtistAlbums_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetArtistAlbums_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid artistId = await SeedArtistAsync(libraryId);
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetArtistAlbums_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
+ Guid otherArtistId = await SeedArtistAsync(otherLibraryId);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums";
+
+ // 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 GetArtistAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetArtistAlbums_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task GetArtistAlbums_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
+ }
+
+ ///
+ /// 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 belonging to the media library identified by .
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The Id of the seeded artist.
+ private async Task SeedArtistAsync(Guid libraryId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid artistId = Guid.NewGuid();
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return artistId;
+ }
+
+ ///
+ /// Seeds an album belonging to the artist identified by .
+ ///
+ /// The Id of the media library the album belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The title of the album.
+ /// A task representing the asynchronous operation.
+ private async Task SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ dbContext.Albums.Add(_albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false));
+ await dbContext.SaveChangesAsync();
+ }
+
+ ///
+ /// 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/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs
new file mode 100644
index 00000000..43ae7fdc
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs
@@ -0,0 +1,337 @@
+#region ========================================================================= USING =====================================================================================
+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.Albums;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite;
+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.Artists.GetArtistAlbumsLite;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistAlbumsLiteEndpointTests : 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 GetArtistAlbumsLiteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task GetArtistAlbumsLite_WhenArtistHasAlbums_ShouldReturnAlbumLiteDetails()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid artistId = await SeedArtistAsync(libraryId);
+ await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
+ await SeedAlbumAsync(libraryId, artistId, "News of the World");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/lite");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ PaginatedResponse? albums = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(albums);
+ Assert.Equal(2, albums!.Count);
+ Assert.Equal(2, albums.Data.Count);
+ Assert.Contains(albums.Data, album => album.Title == "A Night at the Opera");
+ Assert.Contains(albums.Data, album => album.Title == "News of the World");
+ }
+
+ [Fact]
+ public async Task GetArtistAlbumsLite_WhenArtistHasNoAlbums_ShouldReturnEmptyPaginatedResponse()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid artistId = await SeedArtistAsync(libraryId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/lite");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ PaginatedResponse? albums = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(albums);
+ Assert.Empty(albums!.Data);
+ Assert.Equal(0, albums.Count);
+ }
+
+ [Fact]
+ public async Task GetArtistAlbumsLite_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/lite";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task GetArtistAlbumsLite_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ Guid otherLibraryId = await SeedLibraryAsync(otherUserId);
+ Guid otherArtistId = await SeedArtistAsync(otherLibraryId);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/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 GetArtistAlbumsLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetArtistAlbumsLite_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/not-a-guid/artists/{Guid.NewGuid()}/albums/lite";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task GetArtistAlbumsLite_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/not-a-guid/albums/lite";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
+ }
+
+ ///
+ /// 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 belonging to the media library identified by .
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The Id of the seeded artist.
+ private async Task SeedArtistAsync(Guid libraryId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid artistId = Guid.NewGuid();
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return artistId;
+ }
+
+ ///
+ /// Seeds an album belonging to the artist identified by .
+ ///
+ /// The Id of the media library the album belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The title of the album.
+ /// A task representing the asynchronous operation.
+ private async Task SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ dbContext.Albums.Add(_albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false));
+ await dbContext.SaveChangesAsync();
+ }
+
+ ///
+ /// 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/Artists/GetArtists/GetArtistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs
new file mode 100644
index 00000000..8adf81a4
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs
@@ -0,0 +1,329 @@
+#region ========================================================================= USING =====================================================================================
+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.Artists;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists;
+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.Artists.GetArtists;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistsEndpointTests : 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 UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetArtistsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task GetArtists_WhenCalledWithoutPaginationData_ShouldReturnAllArtists()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ await SeedArtistAsync(libraryId, "Artist A");
+ await SeedArtistAsync(libraryId, "Artist B");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ PaginatedResponse? paginatedArtists = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(paginatedArtists);
+ Assert.Equal(2, paginatedArtists!.Count);
+ Assert.Equal(2, paginatedArtists.Data.Count);
+ Assert.Equal(1, paginatedArtists.CurrentPage);
+ Assert.Contains(paginatedArtists.Data, artist => artist.Name == "Artist A");
+ Assert.Contains(paginatedArtists.Data, artist => artist.Name == "Artist B");
+ }
+
+ [Fact]
+ public async Task GetArtists_WhenCalledWithSearchTerm_ShouldReturnOnlyMatchingArtists()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ await SeedArtistAsync(libraryId, "Fellowship");
+ await SeedArtistAsync(libraryId, "The Two Towers");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists?searchTerm={Uri.EscapeDataString("Fellowship")}");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ PaginatedResponse? paginatedArtists = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(paginatedArtists);
+ ArtistResponse artist = Assert.Single(paginatedArtists!.Data);
+ Assert.Equal("Fellowship", artist.Name);
+ Assert.Equal(1, paginatedArtists.Count);
+ }
+
+ [Fact]
+ public async Task GetArtists_WhenCalledWithPaginationData_ShouldReturnRequestedPage()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ await SeedArtistAsync(libraryId, "Artist A");
+ await SeedArtistAsync(libraryId, "Artist B");
+ await SeedArtistAsync(libraryId, "Artist C");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists?currentPage=2&perPage=2");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ PaginatedResponse? paginatedArtists = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(paginatedArtists);
+ Assert.Equal(3, paginatedArtists!.Count);
+ Assert.Equal(2, paginatedArtists.NumberOfPages);
+ Assert.Equal(2, paginatedArtists.CurrentPage);
+ Assert.Equal(2, paginatedArtists.PerPage);
+ ArtistResponse artist = Assert.Single(paginatedArtists.Data);
+ Assert.Equal("Artist C", artist.Name);
+ }
+
+ [Fact]
+ public async Task GetArtists_WhenNoArtistsExist_ShouldReturnEmptyPaginatedResponse()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ PaginatedResponse? paginatedArtists = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(paginatedArtists);
+ Assert.Empty(paginatedArtists!.Data);
+ Assert.Equal(0, paginatedArtists.Count);
+ }
+
+ [Fact]
+ public async Task GetArtists_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ Guid libraryId = await SeedLibraryAsync(otherUserId);
+ await SeedArtistAsync(libraryId, "Artist A");
+ string url = $"/api/v1/libraries/{libraryId}/artists";
+
+ // 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 GetArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetArtists_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = "/api/v1/libraries/not-a-guid/artists";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
+ }
+
+ ///
+ /// Seeds a 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: "Test Library", libraryType: LibraryType.Music, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds an artist belonging to the media library identified by .
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The name of the artist.
+ /// A task representing the asynchronous operation.
+ private async Task SeedArtistAsync(Guid libraryId, string name)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ }
+
+ ///
+ /// 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 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/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs
new file mode 100644
index 00000000..418651dd
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs
@@ -0,0 +1,279 @@
+#region ========================================================================= USING =====================================================================================
+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.Artists;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite;
+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.Artists.GetArtistsLite;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetArtistsLiteEndpointTests : 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 UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetArtistsLiteEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task GetArtistsLite_WhenCalledWithoutPaginationData_ShouldReturnAllArtists()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ await SeedArtistAsync(libraryId, "Artist A");
+ await SeedArtistAsync(libraryId, "Artist B");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ PaginatedResponse? paginatedArtists = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(paginatedArtists);
+ Assert.Equal(2, paginatedArtists!.Count);
+ Assert.Equal(2, paginatedArtists.Data.Count);
+ Assert.Contains(paginatedArtists.Data, artist => artist.Name == "Artist A");
+ Assert.Contains(paginatedArtists.Data, artist => artist.Name == "Artist B");
+ }
+
+ [Fact]
+ public async Task GetArtistsLite_WhenNoArtistsExist_ShouldReturnEmptyPaginatedResponse()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ PaginatedResponse? paginatedArtists = await response.Content.ReadFromJsonAsync>(_jsonOptions);
+ Assert.NotNull(paginatedArtists);
+ Assert.Empty(paginatedArtists!.Data);
+ Assert.Equal(0, paginatedArtists.Count);
+ }
+
+ [Fact]
+ public async Task GetArtistsLite_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ Guid libraryId = await SeedLibraryAsync(otherUserId);
+ await SeedArtistAsync(libraryId, "Artist A");
+ string url = $"/api/v1/libraries/{libraryId}/artists/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 GetArtistsLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/lite";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetArtistsLite_WhenRouteIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = "/api/v1/libraries/not-a-guid/artists/lite";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
+ }
+
+ ///
+ /// Seeds a 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: "Test Library", libraryType: LibraryType.Music, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds an artist belonging to the media library identified by .
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The name of the artist.
+ /// A task representing the asynchronous operation.
+ private async Task SeedArtistAsync(Guid libraryId, string name)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ }
+
+ ///
+ /// 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 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/Artists/UpdateArtist/UpdateArtistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs
new file mode 100644
index 00000000..56f138c8
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs
@@ -0,0 +1,349 @@
+#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.Artists;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist;
+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.Artists.UpdateArtist;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateArtistEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+ private readonly UpdateArtistRequestFixture _updateArtistRequestFixture = new();
+ private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = 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