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 class. + /// + /// Injected in-memory API factory. + public UpdateArtistEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task UpdateArtist_WhenCalledByOwnerWithValidData_ShouldUpdateArtistAndPersistChanges() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + (Guid artistId, Guid albumId) = await SeedArtistWithAlbumAsync(libraryId); + UpdateArtistAlbumRequest album = _updateArtistAlbumRequestFixture.Create( + albumId: albumId, + metadata: _albumMetadataDtoFixture.Create(title: "Updated Album"), + contributors: [], + ratings: [], + tracks: []); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(name: "Queen Updated", contributors: [], albums: [album]); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + ArtistResponse? artistResponse = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(artistResponse); + Assert.Equal(artistId, artistResponse!.Id); + Assert.Equal("Queen Updated", artistResponse.Name); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity storedArtist = dbContext.Artists.Single(artist => artist.Id == artistId); + Assert.Equal("Queen Updated", storedArtist.Name); + } + + [Fact] + public async Task UpdateArtist_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertNotFoundAsync(response, "ArtistNotFound", url); + } + + [Fact] + public async Task UpdateArtist_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + (Guid artistId, _) = await SeedArtistWithAlbumAsync(libraryId); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertNotFoundAsync(response, "ArtistNotFound", url); + } + + [Fact] + public async Task UpdateArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid libraryId = await SeedLibraryAsync(otherUserId); + (Guid artistId, _) = await SeedArtistWithAlbumAsync(libraryId); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4"); + } + + [Fact] + public async Task UpdateArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync(url, request); + + // Assert + await AssertUnauthorizedAsync(response, url); + } + + [Fact] + public async Task UpdateArtist_WhenNameIsMissing_ShouldReturnUnprocessableEntity() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + (Guid artistId, _) = await SeedArtistWithAlbumAsync(libraryId); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(name: string.Empty, contributors: [], albums: []); + string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistNameCannotBeEmpty"); + } + + [Fact] + public async Task UpdateArtist_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + string url = $"/api/v1/libraries/{libraryId}/artists/not-a-guid"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // 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 that owns a single album, both belonging to . + /// + /// The Id of the media library the artist belongs to. + /// The Ids of the seeded artist and album. + private async Task<(Guid artistId, Guid albumId)> SeedArtistWithAlbumAsync(Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (artistId, albumId); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Asserts that the response is a not found problem details carrying the expected detail and request instance path. + /// + /// The HTTP response to assert on. + /// The expected problem detail. + /// The expected request instance path. + private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance) + { + await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5"); + } + + /// + /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type. + /// + /// The HTTP response to assert on. + /// The expected HTTP status code. + /// The expected problem title. + /// The expected problem detail. + /// The expected request instance path. + /// The expected problem type URI. + private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType) + { + Assert.Equal(statusCode, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32()); + Assert.Equal(expectedType, problemDetails["type"].GetString()); + Assert.Equal(expectedTitle, problemDetails["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"])); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs new file mode 100644 index 00000000..42a97d3b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs @@ -0,0 +1,208 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +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.Artists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddArtistEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly AddArtistRequestFixture _addArtistRequestFixture = new(); + private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddArtistEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task AddArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artists", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task AddArtist_WhenUnauthorized_ShouldNotLeakSensitiveData() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task AddArtist_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists", request); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddArtist_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousName) + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid libraryId = await SeedLibraryAsync(userId); + AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []); + AddArtistRequest request = _addArtistRequestFixture.Create(name: maliciousName, contributors: [], albums: [album]); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request); + + // Assert + // The malicious name passes validation, reaches the parameterized insert, and is persisted verbatim: if it were + // concatenated into raw SQL, the insert would fail and the artist would not be created. + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await dbContext.Artists.CountAsync(artist => artist.LibraryId == libraryId)); + + } + + [Fact] + public async Task AddArtist_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid libraryId = await SeedLibraryAsync(ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(requesterUsername); + 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/{libraryId}/artists", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a music library owned by . + /// + /// 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; + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs new file mode 100644 index 00000000..97c26687 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs @@ -0,0 +1,233 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteArtistEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteArtistEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task DeleteArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteArtist_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteArtist_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task DeleteArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + [Fact] + public async Task DeleteArtist_WhenArtistBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + (Guid ownLibraryId, _) = await SeedLibraryAndArtistAsync(actingUserId); + + // The artist lives in a library owned by another user, and is referenced through the acting user's own library route. + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (_, Guid victimArtistId) = await SeedLibraryAndArtistAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + // The other user's artist is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId)); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist 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 Reissues", 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); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs new file mode 100644 index 00000000..5ef58622 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs @@ -0,0 +1,195 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetArtistEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtist_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtist_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task GetArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist 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 Reissues", 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); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs new file mode 100644 index 00000000..49dcd05c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs @@ -0,0 +1,192 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetArtistAlbumsEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetArtistAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtistAlbums_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtistAlbums_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task GetArtistAlbums_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist 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 Reissues", 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); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs new file mode 100644 index 00000000..1c681ab4 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs @@ -0,0 +1,192 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetArtistAlbumsLiteEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetArtistAlbumsLite_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtistAlbumsLite_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/lite"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtistAlbumsLite_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/lite"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task GetArtistAlbumsLite_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/lite"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist 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 Reissues", 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); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs new file mode 100644 index 00000000..fa05b321 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs @@ -0,0 +1,194 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetArtistsEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetArtists_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm) + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedArtistAsync(libraryId, "Queen"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal); + + // the injected statement must never be executed: the Artists table and the seeded rows must still be there + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await dbContext.Artists.CountAsync(artist => artist.LibraryId == libraryId)); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtists_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + } + + [Fact] + public async Task GetArtists_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid libraryId = await SeedLibraryAsync(ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(requesterUsername); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a music library owned by . + /// + /// 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 Reissues", 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(); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs new file mode 100644 index 00000000..ec5ae14e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs @@ -0,0 +1,193 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetArtistsLiteEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetArtistsLite_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/lite"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetArtistsLite_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm) + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedArtistAsync(libraryId, "Queen"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal); + + // the injected statement must never be executed: the Artists table and the seeded rows must still be there + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await dbContext.Artists.CountAsync(artist => artist.LibraryId == libraryId)); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtistsLite_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/lite"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + } + + [Fact] + public async Task GetArtistsLite_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid libraryId = await SeedLibraryAsync(ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(requesterUsername); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a 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 Reissues", 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(); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs new file mode 100644 index 00000000..909cc08b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs @@ -0,0 +1,311 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.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.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + 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 List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateArtistEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(401, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task UpdateArtist_WhenUnauthorized_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateArtist_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousName) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + Guid libraryId = Guid.NewGuid(); + (Guid artistId, Guid albumId) = await SeedArtistAsync(libraryId, userId); + UpdateArtistAlbumRequest album = _updateArtistAlbumRequestFixture.Create( + albumId: albumId, + metadata: _albumMetadataDtoFixture.Create(title: "Updated Album"), + contributors: [], + ratings: [], + tracks: []); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(name: maliciousName, contributors: [], albums: [album]); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request); + + // Assert + // The malicious name passes validation, reaches the parameterized update, and is persisted verbatim: if it were + // concatenated into raw SQL, the update would fail and the artist would not be updated. + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId); + Assert.NotNull(storedArtist); + Assert.Equal(maliciousName, storedArtist!.Name); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateArtist_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty"); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateArtist_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty"); + } + + [Fact] + public async Task UpdateArtist_WhenArtistDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + Guid libraryId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Hash", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + } + + [Fact] + public async Task UpdateArtist_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid libraryId = Guid.NewGuid(); + (Guid artistId, _) = await SeedArtistAsync(libraryId, ownerId); + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + _seededUsernames.Add(requesterUsername); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task UpdateArtist_WhenArtistBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + Guid ownLibraryId = Guid.NewGuid(); + await SeedArtistAsync(ownLibraryId, actingUserId); + + // The artist lives in a library owned by another user, and is referenced through the acting user's own library route. + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + Guid victimLibraryId = Guid.NewGuid(); + (Guid victimArtistId, _) = await SeedArtistAsync(victimLibraryId, victimUserId); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(name: "Hijacked", contributors: [], albums: []); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + // The other user's artist is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId); + Assert.NotNull(storedArtist); + Assert.Equal("Queen", storedArtist.Name); + } + + /// + /// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload. + /// + /// The HTTP response to assert. + /// The injected payload that must never be echoed back. + /// The validation error code expected in the response. + private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(injectedPayload, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal); + } + + /// + /// Seeds a music library owned by , together with an artist that owns one album. + /// + /// The Id of the media library to seed. + /// The Id of the user that owns the media library. + /// The Ids of the seeded artist and of its album. + private async Task<(Guid artistId, Guid albumId)> SeedArtistAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (artistId, albumId); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMappingTests.cs new file mode 100644 index 00000000..096e1e44 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMappingTests.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddArtistCommandMappingTests +{ + private readonly AddArtistCommandFixture _addArtistCommandFixture = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistCommand command = _addArtistCommandFixture.Create(); + + // Act + Result result = command.ToDomainEntity(libraryId); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.Equal(libraryId, artist.LibraryId.Value); + Assert.Equal(command.Name, artist.Name); + Assert.True(artist.Website.HasValue); + Assert.Equal(command.Website, artist.Website.Value); + Assert.True(artist.MusicBrainzArtistId.HasValue); + Assert.Equal(command.MusicBrainzArtistId, artist.MusicBrainzArtistId.Value.Value); + Assert.Equal(command.Contributors!.Count, artist.Contributors.Count); + Assert.Equal(command.Albums!.Count, artist.Albums.Count); + Assert.Equal(command.Albums.Select(album => album.Metadata!.Title), artist.Albums.Select(album => album.Metadata.Title)); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistCommand command = _addArtistCommandFixture.Create( + includeWebsite: false, + includeMusicBrainzArtistId: false, + contributors: []); + + // Act + Result result = command.ToDomainEntity(libraryId); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.False(artist.Website.HasValue); + Assert.False(artist.MusicBrainzArtistId.HasValue); + Assert.Empty(artist.Contributors); + Assert.NotEmpty(artist.Albums); + } + + [Fact] + public void ToDomainEntity_WhenAlbumCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddAlbumCommand invalidAlbum = _addAlbumCommandFixture.Create( + metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [invalidAlbum]); + + // Act + Result result = command.ToDomainEntity(libraryId); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenArtistNameIsEmpty_ShouldReturnError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(name: string.Empty); + + // Act + Result result = command.ToDomainEntity(Guid.NewGuid()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenArtistHasNoAlbums_ShouldReturnError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: []); + + // Act + Result result = command.ToDomainEntity(Guid.NewGuid()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMappingTests.cs new file mode 100644 index 00000000..a3d0f649 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMappingTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddArtistRequestMappingTests +{ + private readonly AddArtistRequestFixture _addArtistRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(); + + // Act + AddArtistCommand result = request.ToCommand(libraryId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(request.Name, result.Name); + Assert.Equal(request.Website, result.Website); + Assert.Equal(request.MusicBrainzArtistId, result.MusicBrainzArtistId); + Assert.Equal(request.Contributors, result.Contributors); + Assert.NotNull(result.Albums); + Assert.Equal(request.Albums!.Count, result.Albums.Count); + } + + [Fact] + public void ToCommand_WhenMappingAlbums_ShouldMapEachAlbumToACommandWithTheLibraryIdAndNullArtistId() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(); + + // Act + AddArtistCommand result = request.ToCommand(libraryId.ToString()); + + // Assert + for (int i = 0; i < request.Albums!.Count; i++) + { + Assert.Equal(libraryId.ToString(), result.Albums![i].LibraryId); + Assert.Null(result.Albums[i].ArtistId); + Assert.Equal(request.Albums[i].Metadata, result.Albums[i].Metadata); + Assert.Equal(request.Albums[i].MediaFormat, result.Albums[i].MediaFormat); + Assert.Equal(request.Albums[i].Barcode, result.Albums[i].Barcode); + Assert.Equal(request.Albums[i].CatalogNumber, result.Albums[i].CatalogNumber); + Assert.Equal(request.Albums[i].MusicBrainzReleaseId, result.Albums[i].MusicBrainzReleaseId); + Assert.Equal(request.Albums[i].MusicBrainzReleaseGroupId, result.Albums[i].MusicBrainzReleaseGroupId); + Assert.Equal(request.Albums[i].MusicBrainzReleaseArtistId, result.Albums[i].MusicBrainzReleaseArtistId); + Assert.Equal(request.Albums[i].Contributors, result.Albums[i].Contributors); + Assert.Equal(request.Albums[i].Ratings, result.Albums[i].Ratings); + Assert.Null(result.Albums[i].AlbumId); + } + } + + [Fact] + public void ToCommand_WhenAlbumsAreMissing_ShouldMapNullAlbums() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(includeAlbums: false); + + // Act + AddArtistCommand result = request.ToCommand(Guid.NewGuid().ToString()); + + // Assert + Assert.Null(result.Albums); + } + + [Fact] + public void ToCommand_WhenRouteIdIsNull_ShouldMapNullRouteId() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + + // Act + AddArtistCommand result = request.ToCommand(null); + + // Assert + Assert.Null(result.LibraryId); + } + + [Fact] + public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapNulls() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create( + includeWebsite: false, + includeMusicBrainzArtistId: false, + includeAlbums: false); + + // Act + AddArtistCommand result = request.ToCommand(Guid.NewGuid().ToString()); + + // Assert + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Null(result.Albums); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMappingTests.cs new file mode 100644 index 00000000..96fe6768 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMappingTests.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistEntityMappingTests +{ + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingValidArtistEntity_ShouldMapAllPropertiesCorrectly() + { + // Arrange + ArtistEntity entity = _artistEntityFixture.Create(); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.Equal(entity.Id, artist.Id.Value); + Assert.Equal(entity.LibraryId, artist.LibraryId.Value); + Assert.Equal(entity.Name, artist.Name); + Assert.True(artist.Website.HasValue); + Assert.Equal(entity.Website, artist.Website.Value); + Assert.True(artist.MusicBrainzArtistId.HasValue); + Assert.Equal(entity.MusicBrainzArtistId, artist.MusicBrainzArtistId.Value.Value); + Assert.Equal(entity.Contributors.Select(contributor => contributor.MediaContributorId), artist.Contributors.Select(contributor => contributor.ContributorId.Value)); + Assert.Equal(entity.Contributors.Select(contributor => contributor.Role), artist.Contributors.Select(contributor => contributor.Role)); + Assert.Equal(entity.Albums.Count, artist.Albums.Count); + Assert.Equal(entity.Albums.Select(album => album.Id), artist.Albums.Select(album => album.Id.Value)); + Assert.Equal(entity.Albums.Select(album => album.Title), artist.Albums.Select(album => album.Metadata.Title)); + Assert.Equal(entity.CreatedOnUtc, artist.CreatedOnUtc); + Assert.True(artist.UpdatedOnUtc.HasValue); + Assert.Equal(entity.UpdatedOnUtc, artist.UpdatedOnUtc.Value); + } + + [Fact] + public void ToDomainEntity_WhenAlbumCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity invalidAlbum = _albumEntityFixture.Create( + libraryId: libraryId, + originalReleaseDate: new DateOnly(2000, 1, 1), + originalReleaseYear: 1999); + ArtistEntity entity = _artistEntityFixture.Create(libraryId: libraryId, albums: [invalidAlbum]); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones() + { + // Arrange + ArtistEntity entity = _artistEntityFixture.Create( + includeMetadata: false, + includeWebsite: false, + includeMusicBrainzArtistId: false, + includeContributors: false); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.False(artist.Website.HasValue); + Assert.False(artist.MusicBrainzArtistId.HasValue); + Assert.Empty(artist.Contributors); + Assert.Single(artist.Albums); + } + + [Fact] + public void ToResponse_WhenMappingArtistEntity_ShouldMapAllPropertiesCorrectly() + { + // Arrange + ArtistEntity entity = _artistEntityFixture.Create(); + + // Act + ArtistResponse result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(entity.Id, result.Id); + Assert.Equal(entity.LibraryId, result.LibraryId); + Assert.Equal(entity.Name, result.Name); + Assert.Equal(entity.Website, result.Website); + Assert.Equal(entity.MusicBrainzArtistId, result.MusicBrainzArtistId); + Assert.Equal(entity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role)), result.Contributors); + Assert.Equal(entity.Albums.Count, result.Albums!.Count); + Assert.Equal(entity.Albums.Select(album => album.Id), result.Albums.Select(album => album.Id)); + Assert.Equal(entity.Albums.Select(album => album.Title), result.Albums.Select(album => album.Metadata.Title)); + Assert.Equal(entity.CreatedOnUtc, result.CreatedOnUtc); + Assert.Equal(entity.UpdatedOnUtc, result.UpdatedOnUtc); + } + + [Fact] + public void ToResponse_WhenOptionalPropertiesAreMissing_ShouldMapNullsAndEmptyCollections() + { + // Arrange + ArtistEntity entity = _artistEntityFixture.Create( + includeMetadata: false, + includeWebsite: false, + includeMusicBrainzArtistId: false, + includeContributors: false); + + // Act + ArtistResponse result = entity.ToResponse(); + + // Assert + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Empty(result.Contributors!); + Assert.Single(result.Albums!); + } + + [Fact] + public void ToResponses_WhenMappingMultipleArtistEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _artistEntityFixture.CreateMany(2); + + // Act + IReadOnlyList results = entities.ToResponses(); + + // Assert + Assert.NotNull(results); + Assert.Equal(entities.Count, results.Count); + for (int i = 0; i < entities.Count; i++) + { + Assert.Equal(entities[i].Id, results[i].Id); + Assert.Equal(entities[i].Name, results[i].Name); + } + } + + [Fact] + public void ToResponses_WhenMappingPaginatedArtistEntities_ShouldMapAllPropertiesCorrectly() + { + // Arrange + List entities = _artistEntityFixture.CreateMany(2); + PaginatedResultDto paginatedEntities = _paginatedResultDtoFixture.Create( + data: entities, + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + + // Act + PaginatedResponse result = paginatedEntities.ToResponses(); + + // Assert + Assert.NotNull(result); + Assert.Equal(paginatedEntities.Data.Count, result.Data.Count); + Assert.Equal(paginatedEntities.CurrentPage, result.CurrentPage); + Assert.Equal(paginatedEntities.PerPage, result.PerPage); + Assert.Equal(paginatedEntities.Count, result.Count); + Assert.Equal(paginatedEntities.NumberOfPages, result.NumberOfPages); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowMappingTests.cs new file mode 100644 index 00000000..e630aa00 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowMappingTests.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistLiteRowMappingTests +{ + private readonly ArtistLiteRowFixture _artistLiteRowFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + [Fact] + public void ToResponse_WhenMappingArtistLiteRow_ShouldMapAllPropertiesCorrectly() + { + // Arrange + ArtistLiteRow readModel = _artistLiteRowFixture.Create(); + + // Act + ArtistLiteResponse result = readModel.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(readModel.Id, result.Id); + Assert.Equal(readModel.Name, result.Name); + } + + [Fact] + public void ToResponses_WhenMappingMultipleArtistLiteRows_ShouldMapAllCorrectly() + { + // Arrange + List readModels = _artistLiteRowFixture.CreateMany(2); + + // Act + IReadOnlyList results = readModels.ToResponses(); + + // Assert + Assert.NotNull(results); + Assert.Equal(readModels.Count, results.Count); + Assert.Equal(readModels.Select(readModel => readModel.Id), results.Select(response => response.Id)); + Assert.Equal(readModels.Select(readModel => readModel.Name), results.Select(response => response.Name)); + } + + [Fact] + public void ToResponses_WhenMappingPaginatedArtistLiteRows_ShouldMapAllPropertiesCorrectly() + { + // Arrange + List readModels = _artistLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedReadModels = _paginatedResultDtoFixture.Create( + data: readModels, + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + + // Act + PaginatedResponse result = paginatedReadModels.ToResponses(); + + // Assert + Assert.NotNull(result); + Assert.Equal(paginatedReadModels.Data.Count, result.Data.Count); + Assert.Equal(paginatedReadModels.CurrentPage, result.CurrentPage); + Assert.Equal(paginatedReadModels.PerPage, result.PerPage); + Assert.Equal(paginatedReadModels.Count, result.Count); + Assert.Equal(paginatedReadModels.NumberOfPages, result.NumberOfPages); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMappingTests.cs new file mode 100644 index 00000000..04bab90f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMappingTests.cs @@ -0,0 +1,158 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistMappingTests +{ + private readonly ArtistFixture _artistFixture = new(); + private readonly AlbumFixture _albumFixture = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingCompleteArtist_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Artist artist = _artistFixture.Create(); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.Equal(artist.Id.Value, result.Id); + Assert.Equal(artist.LibraryId.Value, result.LibraryId); + Assert.Equal(artist.Name, result.Name); + Assert.Equal(artist.Website.Value, result.Website); + Assert.Equal(artist.MusicBrainzArtistId.Value.Value, result.MusicBrainzArtistId); + Assert.Equal(artist.CreatedOnUtc, result.CreatedOnUtc); + Assert.Equal(Guid.Empty, result.CreatedBy); + Assert.Null(result.UpdatedOnUtc); + Assert.Null(result.UpdatedBy); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingContributors_ShouldCreateAContributorEntityPerContributor() + { + // Arrange + Artist artist = _artistFixture.Create(); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.Equal(artist.Contributors.Count, result.Contributors.Count); + for (int i = 0; i < artist.Contributors.Count; i++) + { + MusicMediaContributor contributor = artist.Contributors.ElementAt(i); + ArtistContributorEntity contributorEntity = result.Contributors[i]; + Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId); + Assert.Equal(contributor.Role, contributorEntity.Role); + Assert.Equal(artist.Id.Value, contributorEntity.ArtistId); + Assert.Equal(artist.CreatedOnUtc, contributorEntity.CreatedOnUtc); + Assert.Equal(Guid.Empty, contributorEntity.CreatedBy); + Assert.Null(contributorEntity.UpdatedBy); + } + } + + [Fact] + public void ToRepositoryEntity_WhenMappingAlbums_ShouldCreateAnAlbumEntityPerAlbum() + { + // Arrange + Artist artist = _artistFixture.Create(); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.Equal(artist.Albums.Count, result.Albums.Count); + for (int i = 0; i < artist.Albums.Count; i++) + { + Album album = artist.Albums.ElementAt(i); + AlbumEntity albumEntity = result.Albums[i]; + Assert.Equal(album.Id.Value, albumEntity.Id); + Assert.Equal(artist.Id.Value, albumEntity.ArtistId); + Assert.Equal(artist.LibraryId.Value, albumEntity.LibraryId); + Assert.Equal(album.Metadata.Title, albumEntity.Title); + } + } + + [Fact] + public void ToRepositoryEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNulls() + { + // Arrange + Album album = _albumFixture.Create( + mediaFormat: Optional.None(), + barcode: Optional.None(), + catalogNumber: Optional.None(), + musicBrainzReleaseId: Optional.None(), + musicBrainzReleaseGroupId: Optional.None(), + musicBrainzReleaseArtistId: Optional.None()); + Artist artist = _artistFixture.Create( + website: Optional.None(), + musicBrainzArtistId: Optional.None(), + contributors: [], + albums: [album]); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Empty(result.Contributors); + Assert.Single(result.Albums); + Assert.Null(result.Albums[0].MediaFormat); + Assert.Null(result.Albums[0].Barcode); + Assert.Null(result.Albums[0].CatalogNumber); + Assert.Null(result.Albums[0].MusicBrainzReleaseId); + Assert.Null(result.Albums[0].MusicBrainzReleaseGroupId); + Assert.Null(result.Albums[0].MusicBrainzReleaseArtistId); + } + + [Fact] + public void ToRepositoryEntity_WhenWebsiteIsProvided_ShouldMapIt() + { + // Arrange + string website = "https://www.queenonline.com"; + Artist artist = _artistFixture.Create(website: Optional.Some(website)); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.Equal(website, result.Website); + } + + [Fact] + public void ToRepositoryEntity_WhenMusicBrainzArtistIdIsProvided_ShouldMapIt() + { + // Arrange + MusicBrainzId musicBrainzArtistId = _musicBrainzIdFixture.Create(); + Artist artist = _artistFixture.Create(musicBrainzArtistId: Optional.Some(musicBrainzArtistId)); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.Equal(musicBrainzArtistId.Value, result.MusicBrainzArtistId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMappingTests.cs new file mode 100644 index 00000000..1e22eff7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMappingTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteRequestMappingTests +{ + private readonly GetArtistAlbumsLiteRequestFixture _getArtistAlbumsLiteRequestFixture = new(); + + [Fact] + public void ToQuery_WhenCalledWithRouteIds_ShouldMapRouteIdsFromArguments() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + + // Act + GetArtistAlbumsLiteQuery result = request.ToQuery("library-route", "artist-route"); + + // Assert + Assert.Equal("library-route", result.LibraryId); + Assert.Equal("artist-route", result.ArtistId); + } + + [Fact] + public void ToQuery_WhenNoPaginationValuesAreProvided_ShouldMapNullPaginationData() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + + // Act + GetArtistAlbumsLiteQuery result = request.ToQuery("library-route", "artist-route"); + + // Assert + Assert.Null(result.PaginationData); + } + + [Fact] + public void ToQuery_WhenOnlyCurrentPageIsProvided_ShouldDefaultPerPageToTwoHundred() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(currentPage: 3, includePerPage: false); + + // Act + GetArtistAlbumsLiteQuery result = request.ToQuery("library-route", "artist-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(3, result.PaginationData.CurrentPage); + Assert.Equal(200, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenOnlyPerPageIsProvided_ShouldDefaultCurrentPageToOne() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(perPage: 50, includeCurrentPage: false); + + // Act + GetArtistAlbumsLiteQuery result = request.ToQuery("library-route", "artist-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(1, result.PaginationData.CurrentPage); + Assert.Equal(50, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenBothPaginationValuesAreProvided_ShouldMapThem() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(currentPage: 2, perPage: 25); + + // Act + GetArtistAlbumsLiteQuery result = request.ToQuery("library-route", "artist-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(2, result.PaginationData.CurrentPage); + Assert.Equal(25, result.PaginationData.PerPage); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMappingTests.cs new file mode 100644 index 00000000..9f8c28df --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMappingTests.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteRequestMappingTests +{ + private readonly GetArtistsLiteRequestFixture _getArtistsLiteRequestFixture = new(); + + [Fact] + public void ToQuery_WhenCalledWithRouteId_ShouldMapRouteIdFromArgument() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Equal("library-route", result.LibraryId); + } + + [Fact] + public void ToQuery_WhenSearchTermIsProvided_ShouldMapIt() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(searchTerm: "queen"); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Equal("queen", result.SearchTerm); + } + + [Fact] + public void ToQuery_WhenNoPaginationValuesAreProvided_ShouldMapNullPaginationData() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Null(result.PaginationData); + } + + [Fact] + public void ToQuery_WhenOnlyCurrentPageIsProvided_ShouldDefaultPerPageToTwoHundred() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(currentPage: 3, includePerPage: false); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(3, result.PaginationData.CurrentPage); + Assert.Equal(200, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenOnlyPerPageIsProvided_ShouldDefaultCurrentPageToOne() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(perPage: 50, includeCurrentPage: false); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(1, result.PaginationData.CurrentPage); + Assert.Equal(50, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenBothPaginationValuesAreProvided_ShouldMapThem() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(currentPage: 2, perPage: 25); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(2, result.PaginationData.CurrentPage); + Assert.Equal(25, result.PaginationData.PerPage); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMappingTests.cs new file mode 100644 index 00000000..9809bb01 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMappingTests.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsRequestMappingTests +{ + private readonly GetArtistsRequestFixture _getArtistsRequestFixture = new(); + + [Fact] + public void ToQuery_WhenCalledWithRouteId_ShouldMapRouteIdFromArgument() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Equal("library-route", result.LibraryId); + } + + [Fact] + public void ToQuery_WhenSearchTermIsProvided_ShouldMapIt() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(searchTerm: "queen"); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Equal("queen", result.SearchTerm); + } + + [Fact] + public void ToQuery_WhenNoPaginationValuesAreProvided_ShouldMapNullPaginationData() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Null(result.PaginationData); + } + + [Fact] + public void ToQuery_WhenOnlyCurrentPageIsProvided_ShouldDefaultPerPageToTwoHundred() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(currentPage: 3, includePerPage: false); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(3, result.PaginationData.CurrentPage); + Assert.Equal(200, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenOnlyPerPageIsProvided_ShouldDefaultCurrentPageToOne() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(perPage: 50, includeCurrentPage: false); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(1, result.PaginationData.CurrentPage); + Assert.Equal(50, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenBothPaginationValuesAreProvided_ShouldMapThem() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(currentPage: 2, perPage: 25); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(2, result.PaginationData.CurrentPage); + Assert.Equal(25, result.PaginationData.PerPage); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMappingTests.cs new file mode 100644 index 00000000..9382e008 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMappingTests.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistAlbumRequestMappingTests +{ + private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistAlbumRequest request = _updateArtistAlbumRequestFixture.Create(); + + // Act + AddAlbumCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(artistId.ToString(), result.ArtistId); + Assert.Equal(request.Metadata, result.Metadata); + Assert.Equal(request.MediaFormat, result.MediaFormat); + Assert.Equal(request.Barcode, result.Barcode); + Assert.Equal(request.CatalogNumber, result.CatalogNumber); + Assert.Equal(request.MusicBrainzReleaseId, result.MusicBrainzReleaseId); + Assert.Equal(request.MusicBrainzReleaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal(request.MusicBrainzReleaseArtistId, result.MusicBrainzReleaseArtistId); + Assert.Equal(request.Contributors, result.Contributors); + Assert.Equal(request.Ratings, result.Ratings); + Assert.Equal(request.AlbumId, result.AlbumId); + Assert.NotNull(result.Tracks); + Assert.Equal(request.Tracks!.Count, result.Tracks.Count); + } + + [Fact] + public void ToCommand_WhenMappingTracks_ShouldMapEachTrackToACommandWithTheLibraryIdAndArtistIdAndNullAlbumId() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistAlbumRequest request = _updateArtistAlbumRequestFixture.Create(); + + // Act + AddAlbumCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + for (int i = 0; i < request.Tracks!.Count; i++) + { + AddTrackCommand trackCommand = result.Tracks![i]; + Assert.Equal(libraryId.ToString(), trackCommand.LibraryId); + Assert.Equal(artistId.ToString(), trackCommand.ArtistId); + Assert.Null(trackCommand.AlbumId); + Assert.Equal(request.Tracks[i].TrackId, trackCommand.TrackId); + Assert.Equal(request.Tracks[i].Path, trackCommand.Path); + Assert.Equal(request.Tracks[i].Metadata, trackCommand.Metadata); + Assert.Equal(request.Tracks[i].TrackNumber, trackCommand.TrackNumber); + } + } + + [Fact] + public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNulls() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistAlbumRequest request = _updateArtistAlbumRequestFixture.Create( + includeAlbumId: false, + includeMediaFormat: false, + includeBarcode: false, + includeCatalogNumber: false, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false, + includeMusicBrainzReleaseArtistId: false, + includeTracks: false); + + // Act + AddAlbumCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + Assert.NotNull(result.Metadata); + Assert.Null(result.AlbumId); + Assert.Null(result.MediaFormat); + Assert.Null(result.Barcode); + Assert.Null(result.CatalogNumber); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Null(result.MusicBrainzReleaseArtistId); + Assert.Null(result.Tracks); + } + + [Fact] + public void ToCommand_WhenRouteIdsAreNull_ShouldMapNullRouteIds() + { + // Arrange + UpdateArtistAlbumRequest request = _updateArtistAlbumRequestFixture.Create(); + + // Act + AddAlbumCommand result = request.ToCommand(null, null); + + // Assert + Assert.Null(result.LibraryId); + Assert.Null(result.ArtistId); + } + + [Fact] + public void ToCommands_WhenMappingMultipleRequests_ShouldMapEachRequest() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + List requests = _updateArtistAlbumRequestFixture.CreateMany(3); + + // Act + List result = [.. requests.ToCommands(libraryId.ToString(), artistId.ToString())]; + + // Assert + Assert.Equal(requests.Count, result.Count); + for (int i = 0; i < requests.Count; i++) + { + Assert.Equal(requests[i].Metadata, result[i].Metadata); + Assert.Equal(requests[i].AlbumId, result[i].AlbumId); + Assert.Equal(libraryId.ToString(), result[i].LibraryId); + Assert.Equal(artistId.ToString(), result[i].ArtistId); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs new file mode 100644 index 00000000..907a816d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs @@ -0,0 +1,274 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCommandMappingTests +{ + private readonly UpdateArtistCommandFixture _updateArtistCommandFixture = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + string updatedPath = "/music/queen/a-night-at-the-opera/03-you-re-my-best-friend.flac"; + AddTrackCommand trackCommand = _addTrackCommandFixture.Create(trackId: trackId, path: updatedPath, trackNumber: 7); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [trackCommand]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(artist, result.Value); + Assert.Equal(command.Name, result.Value.Name); + Assert.True(result.Value.Website.HasValue); + Assert.Equal(command.Website, result.Value.Website.Value); + Assert.True(result.Value.MusicBrainzArtistId.HasValue); + Assert.Equal(command.MusicBrainzArtistId, result.Value.MusicBrainzArtistId.Value.Value); + Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count); + Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId); + Assert.Equal(albumCommand.Metadata!.Title, updatedAlbum.Metadata.Title); + Track updatedTrack = updatedAlbum.Tracks.First(track => track.Id.Value == trackId); + Assert.Equal(updatedPath, updatedTrack.Path); + Assert.Equal(7, updatedTrack.TrackNumber); + Assert.True(updatedTrack.DiscNumber.HasValue); + Assert.Equal(trackCommand.DiscNumber, updatedTrack.DiscNumber.Value); + Assert.Equal(trackCommand.Moods!.Count, updatedTrack.Moods.Count); + Assert.Equal(trackCommand.Isrcs!.Count, updatedTrack.Isrcs.Count); + Assert.Equal(trackCommand.Contributors!.Count, updatedTrack.Contributors.Count); + Assert.Equal(trackCommand.Ratings!.Count, updatedTrack.Ratings.Count); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNones() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddTrackCommand trackCommand = _addTrackCommandFixture.Create( + trackId: trackId, + includeDiscNumber: false, + includeScript: false, + includeKey: false, + includeBpm: false, + includeWork: false, + includeMusicBrainzRecordingId: false, + includeMusicBrainzTrackId: false, + includeMusicBrainzWorkId: false, + includeMoods: false, + includeIsrcs: false, + contributors: [], + ratings: []); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [trackCommand]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + includeWebsite: false, + includeMusicBrainzArtistId: false, + contributors: [], + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.Website.HasValue); + Assert.False(result.Value.MusicBrainzArtistId.HasValue); + Assert.Empty(result.Value.Contributors); + Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId); + Assert.False(updatedTrack.DiscNumber.HasValue); + Assert.False(updatedTrack.Script.HasValue); + Assert.False(updatedTrack.Key.HasValue); + Assert.False(updatedTrack.Bpm.HasValue); + Assert.False(updatedTrack.Work.HasValue); + Assert.Empty(updatedTrack.Moods); + Assert.Empty(updatedTrack.Isrcs); + Assert.Empty(updatedTrack.Contributors); + Assert.Empty(updatedTrack.Ratings); + } + + [Fact] + public void ToDomainEntity_WhenArtistNameIsEmpty_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: []); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + name: string.Empty, + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenAlbumCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddAlbumCommand invalidAlbum = _addAlbumCommandFixture.Create( + albumId: albumId, + metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [invalidAlbum]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenAllAlbumsAreRemoved_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: []); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenAlbumIsNew_ShouldAddItAndRemoveTheStaleOne() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddAlbumCommand newAlbum = _addAlbumCommandFixture.Create(); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [newAlbum]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value.Albums); + Assert.DoesNotContain(result.Value.Albums, album => album.Id.Value == albumId); + } + + [Fact] + public void ToDomainEntity_WhenTrackIsNew_ShouldAddItToTheExistingAlbum() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + Guid newTrackId = Guid.NewGuid(); + AddTrackCommand existingTrack = _addTrackCommandFixture.Create(trackId: trackId); + AddTrackCommand newTrack = _addTrackCommandFixture.Create(trackId: newTrackId); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [existingTrack, newTrack]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId); + Assert.Equal(2, updatedAlbum.Tracks.Count); + Assert.Contains(updatedAlbum.Tracks, track => track.Id.Value == newTrackId); + Assert.Contains(updatedAlbum.Tracks, track => track.Id.Value == trackId); + } + + [Fact] + public void ToDomainEntity_WhenTrackIsStale_ShouldRemoveItFromTheExistingAlbum() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: []); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId); + Assert.Empty(updatedAlbum.Tracks); + } + + /// + /// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to . + /// + /// The Id of the media library the artist belongs to. + /// The created domain artist, together with the Ids of its album and track. + private (Artist artist, Guid albumId, Guid trackId) CreateDomainArtist(Guid libraryId) + { + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + AlbumEntity albumEntity = _albumEntityFixture.Create( + id: albumId, + libraryId: libraryId, + tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]); + ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]); + Result artistResult = artistEntity.ToDomainEntity(); + return (artistResult.Value, albumId, trackId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMappingTests.cs new file mode 100644 index 00000000..c0409b09 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMappingTests.cs @@ -0,0 +1,108 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistRequestMappingTests +{ + private readonly UpdateArtistRequestFixture _updateArtistRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + UpdateArtistCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(artistId.ToString(), result.ArtistId); + Assert.Equal(request.Name, result.Name); + Assert.Equal(request.Website, result.Website); + Assert.Equal(request.MusicBrainzArtistId, result.MusicBrainzArtistId); + Assert.Equal(request.Contributors, result.Contributors); + Assert.NotNull(result.Albums); + Assert.Equal(request.Albums!.Count, result.Albums.Count); + } + + [Fact] + public void ToCommand_WhenMappingAlbums_ShouldMapEachAlbumToACommandWithTheLibraryIdAndArtistId() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + UpdateArtistCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + for (int i = 0; i < request.Albums!.Count; i++) + { + Assert.Equal(libraryId.ToString(), result.Albums![i].LibraryId); + Assert.Equal(artistId.ToString(), result.Albums[i].ArtistId); + Assert.Equal(request.Albums[i].AlbumId, result.Albums[i].AlbumId); + Assert.Equal(request.Albums[i].Metadata, result.Albums[i].Metadata); + } + } + + [Fact] + public void ToCommand_WhenAlbumsAreMissing_ShouldMapNullAlbums() + { + // Arrange + UpdateArtistRequest request = _updateArtistRequestFixture.Create(includeAlbums: false); + + // Act + UpdateArtistCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Assert + Assert.Null(result.Albums); + } + + [Fact] + public void ToCommand_WhenRouteIdsAreNull_ShouldMapNullRouteIds() + { + // Arrange + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + UpdateArtistCommand result = request.ToCommand(null, null); + + // Assert + Assert.Null(result.LibraryId); + Assert.Null(result.ArtistId); + } + + [Fact] + public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapNulls() + { + // Arrange + UpdateArtistRequest request = _updateArtistRequestFixture.Create( + includeWebsite: false, + includeMusicBrainzArtistId: false, + includeAlbums: false); + + // Act + UpdateArtistCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Assert + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Null(result.Albums); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMappingTests.cs index 09abbad2..8b71261a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMappingTests.cs @@ -63,7 +63,16 @@ public class UpdateArtistTrackRequestMappingTests UpdateArtistTrackRequest request = _updateArtistTrackRequestFixture.Create( path: "/music/queen/bohemian-rhapsody.flac", metadata: _audioMetadataDtoFixture.Create(title: "Love of My Life"), - includeOptionalProperties: false, + includeDiscNumber: false, + includeScript: false, + includeKey: false, + includeBpm: false, + includeWork: false, + includeMusicBrainzRecordingId: false, + includeMusicBrainzTrackId: false, + includeMusicBrainzWorkId: false, + includeMoods: false, + includeIsrcs: false, includeTrackId: false); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandlerTests.cs new file mode 100644 index 00000000..3d13c57e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandlerTests.cs @@ -0,0 +1,391 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddArtistCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly IPathService _mockPathService; + private readonly AddArtistCommandHandler _sut; + private readonly Guid _userId; + private readonly AddArtistCommandFixture _addArtistCommandFixture = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddArtistCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockPathService = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + // Default stub: saving changes succeeds. + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + // Default stubs: the validator passes, the current user is authenticated and the library ownership policy allows access. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + // Default stubs: the library exists and the track paths are inside its content locations. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(true); + // Default stub: every referenced media contributor already exists. + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(callInfo => + { + IReadOnlyCollection contributorIds = callInfo.Arg>(); + return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); + }); + // Default stubs: inserting the artist succeeds and the persisted artist can be read back by its Id. + _mockArtistRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_artistEntityFixture.Create(id: callInfo.Arg(), includeAlbums: false, includeContributors: false))); + + _sut = new AddArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Music.ArtistNameCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackPathIsNotWithinLibraryContentLocations_ShouldReturnFailureResult() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + // A single content location makes the path check deterministic, so it can be asserted to have run exactly once per track path. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(contentLocations: ["/music"]))); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError); + _mockPathService.Received(1).IsPathWithin(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnMediaContributorNotFoundError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository() + { + // Arrange + AddAlbumCommand album = _addAlbumCommandFixture.Create(contributors: [], tracks: [_addTrackCommandFixture.Create(contributors: [])]); + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [], albums: [album]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(name: string.Empty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryInsertFails_ShouldReturnFailureResultWithoutSavingChanges() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockArtistRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingTheArtist() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPersistedArtistCannotBeRead_ShouldReturnFailureResult() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenPersistedArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldPersistTheArtistAndReturnItsResponse() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + ArtistEntity? insertedArtist = null; + _mockArtistRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + insertedArtist = callInfo.Arg(); + return Result.Created; + }); + ArtistEntity? persistedArtist = null; + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + persistedArtist = _artistEntityFixture.Create(id: callInfo.Arg(), includeAlbums: false, includeContributors: false); + return Result.From(persistedArtist); + }); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(insertedArtist); + Assert.NotNull(persistedArtist); + Assert.Equal(insertedArtist!.Id, persistedArtist!.Id); + Assert.Equal(persistedArtist.Id, result.Value.Id); + Assert.Equal(persistedArtist.Name, result.Value.Name); + await _mockArtistRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidatorTests.cs new file mode 100644 index 00000000..b81d44b5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidatorTests.cs @@ -0,0 +1,2814 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +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 System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddArtistCommandValidatorTests +{ + private readonly AddArtistCommandFixture _addArtistCommandFixture = new(); + private readonly AddArtistCommandValidator _validator = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(includeName: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name, which the not empty rule rejects + public void Validate_WhenNameIsEmpty_ShouldHaveValidationError(string name) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(name: name); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(name: new Faker().Random.String2(256)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(name: new Faker().Random.String2(255)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteExceeds2048Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(website: new Faker().Random.String2(2049)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(includeWebsite: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(website: new Faker().Internet.Url()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(musicBrainzArtistId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(includeMusicBrainzArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(musicBrainzArtistId: Guid.NewGuid()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(includeContributors: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(includeAlbums: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMetadata: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumTitleIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTitle: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty title + [InlineData(" ")] // whitespace title, which the not empty rule rejects + public void Validate_WhenAlbumTitleIsEmpty_ShouldHaveValidationError(string title) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: title))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: (MusicReleaseType)999))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseType: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: MusicReleaseType.Album))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseStatus: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Theory] + [InlineData(0)] // zero is not a valid total discs value + [InlineData(-1)] // a negative total discs value is not valid + public void Validate_WhenAlbumTotalDiscsIsNotPositive_ShouldHaveValidationError(int totalDiscs) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: totalDiscs))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalDiscsIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalDiscs: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalDiscsIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: 2))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid total tracks value + [InlineData(-1)] // a negative total tracks value is not valid + public void Validate_WhenAlbumTotalTracksIsNotPositive_ShouldHaveValidationError(int totalTracks) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: totalTracks))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalTracksIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalTracks: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalTracksIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: 10))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseInfo: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReleaseVersionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenAlbumReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenAlbumReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenAlbumGenresIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeGenres: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumGenreNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumTagsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTags: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumTagNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeLanguage: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumMediaFormatIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(mediaFormat: (MusicMediaFormat)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenAlbumMediaFormatIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenAlbumMediaFormatIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(mediaFormat: MusicMediaFormat.CD)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenAlbumCatalogNumberExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(51))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumCatalogNumberIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumBarcodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: string.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Theory] + [InlineData("123")] // too short to be a barcode + [InlineData("abcdefghijkl")] // not numeric + [InlineData("12345678901234")] // too long to be a barcode + public void Validate_WhenAlbumBarcodeHasInvalidFormat_ShouldHaveValidationError(string barcode) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: barcode)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Theory] + [InlineData("123456789012")] // 12 digit barcode + [InlineData("1234567890123")] // 13 digit barcode + public void Validate_WhenAlbumBarcodeIsValid_ShouldNotHaveValidationError(string barcode) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: barcode)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Fact] + public void Validate_WhenAlbumBarcodeIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseGroupIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseGroupId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseArtistIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseArtistId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzIdsAreNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeContributors: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeRatings: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenAlbumRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(includeValue: false, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenAlbumRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingMaxValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, includeMaxValue: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumTracksIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeTracks: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TracksListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackPathIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includePath: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty path + [InlineData(" ")] // whitespace path, which the not empty rule rejects + public void Validate_WhenTrackPathIsEmpty_ShouldHaveValidationError(string path) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: path)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackPathExceeds2048Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".flac")])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenTrackPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2000) + ".flac")])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeMetadata: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackTitleIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenTrackReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReleaseVersionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenTrackReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenTrackReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenTrackGenresIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackGenreNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackTagsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackTagNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzRecordingIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzTrackIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzTrackId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeTrackNumber: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid track number + [InlineData(-1)] // a negative track number is not valid + public void Validate_WhenTrackNumberIsNotPositive_ShouldHaveValidationError(int trackNumber) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackNumber: trackNumber)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid disc number + [InlineData(-1)] // a negative disc number is not valid + public void Validate_WhenDiscNumberIsNotPositive_ShouldHaveValidationError(int discNumber) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(discNumber: discNumber)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackScriptExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(script: new Faker().Random.String2(51))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackKeyIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(key: (MusicKey)999)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Theory] + [InlineData(0)] // zero is not a valid tempo + [InlineData(-1)] // a negative tempo is not valid + public void Validate_WhenTrackBpmIsNotPositive_ShouldHaveValidationError(int bpm) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(bpm: bpm)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackWorkExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(256))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMoodNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(includeName: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIsrcValueIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(includeValue: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeContributors: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenTrackRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeRatings: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenTrackRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenTrackRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalTitle: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeDescription: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReleaseVersionIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenAlbumReReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenAlbumReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenAlbumGenresAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumTagsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalLanguage: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumCatalogNumberIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(50))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseId: Guid.NewGuid(), musicBrainzReleaseGroupId: Guid.NewGuid(), musicBrainzReleaseArtistId: Guid.NewGuid())]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReleaseVersionIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenTrackReReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenTrackReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenTrackGenresAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackTagsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.NewGuid(), musicBrainzTrackId: Guid.NewGuid(), musicBrainzWorkId: Guid.NewGuid())])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackNumber: 7)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(discNumber: 1)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackScriptIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackScriptIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(script: new Faker().Random.String2(50))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackKeyIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + public void Validate_WhenTrackKeyIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(key: MusicKey.CMajor)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + public void Validate_WhenTrackBpmIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackBpmIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(bpm: 120)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackWorkIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackWorkIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(255))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMoodNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(name: "dramatic")])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackMoodsIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIsrcValueIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: "GBUM71029604")])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIsrcsIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenTrackRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs new file mode 100644 index 00000000..19f1198a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs @@ -0,0 +1,306 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteArtistCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly DeleteArtistCommandHandler _sut; + private readonly Guid _userId; + private readonly DeleteArtistCommandFixture _deleteArtistCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeleteArtistCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist deletion succeeds and saving changes succeeds. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockArtistRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.Success); + + _sut = new DeleteArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenArtistExists_ShouldDeleteArtistAndReturnDeleted() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Music.ArtistIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutDeleting() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutDeleting() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeleteArtistFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockArtistRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandValidatorTests.cs new file mode 100644 index 00000000..b0c640a1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandValidatorTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteArtistCommandValidatorTests +{ + private readonly DeleteArtistCommandFixture _deleteArtistCommandFixture = new(); + private readonly DeleteArtistCommandValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandlerTests.cs new file mode 100644 index 00000000..35ab36e6 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandlerTests.cs @@ -0,0 +1,572 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly IPathService _mockPathService; + private readonly UpdateArtistCommandHandler _sut; + private readonly Guid _userId; + private readonly UpdateArtistCommandFixture _updateArtistCommandFixture = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateArtistCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockPathService = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + // Default stub: saving changes succeeds. + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + // Default stubs: the validator passes, the current user is authenticated and the library ownership policy allows access. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + // Default stubs: the library exists and the track paths are inside its content locations. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(true); + // Default stub: every referenced media contributor already exists. + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(callInfo => + { + IReadOnlyCollection contributorIds = callInfo.Arg>(); + return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); + }); + // Default stub: updating the artist aggregate succeeds. + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + _sut = new UpdateArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.ArtistNameCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: Guid.NewGuid()); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString()); + StubArtistReads(existingArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutUpdating() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackPathIsNotWithinLibraryContentLocations_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + // A single content location makes the path check deterministic, so it can be asserted to have run exactly once per track path. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(contentLocations: ["/music"]))); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError); + _mockPathService.Received(1).IsPathWithin(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnMediaContributorNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + AddTrackCommand track = _addTrackCommandFixture.Create(contributors: []); + AddAlbumCommand album = _addAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId, contributors: [], tracks: [track]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), contributors: [], albums: [album]); + ArtistEntity persistedArtist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false)], includeContributors: false); + StubArtistReads(existingArtist, persistedArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenExistingArtistDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + ArtistEntity existingArtist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: string.Empty, albums: [album]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), name: string.Empty); + StubArtistReads(existingArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRemovingTheLastAlbumOfTheArtistFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + // An empty albums list makes the mapping treat the only existing album as stale and remove it, which the aggregate forbids. + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albums: [], contributors: []); + StubArtistReads(existingArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryUpdateFails_ShouldReturnFailureResultWithoutSavingChanges() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingTheArtist() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPersistedArtistCannotBeRead_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist, error: ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenPersistedArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist, persistedArtist: null, hasPersistedArtist: true); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldUpdateTheArtistAndReturnItsResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + AddTrackCommand track = _addTrackCommandFixture.Create(); + AddAlbumCommand album = _addAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId, tracks: [track]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albums: [album]); + ArtistEntity persistedArtist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false)], includeContributors: false); + ArtistEntity? updatedArtist = null; + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedArtist = callInfo.Arg(); + return Result.Updated; + }); + StubArtistReads(existingArtist, persistedArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(updatedArtist); + Assert.Equal(artistId, result.Value.Id); + Assert.Equal(persistedArtist.Name, result.Value.Name); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + /// + /// Creates an existing artist that owns a single album, which belongs to the provided library. + /// + /// The Id of the media library the artist belongs to. + /// The Id of the artist. + /// The Id of the album the artist owns. + /// The created artist entity. + private ArtistEntity CreateExistingArtist(Guid libraryId, Guid artistId, Guid albumId) + { + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: true); + return _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [album], includeContributors: true); + } + + /// + /// Stubs the artist repository so that the initial artist read, and optionally the persisted artist read, return the provided entities. + /// + /// The artist returned by the initial read. + /// Optional. The artist returned by the persisted read. When not provided, is returned again. + /// Optional. The error returned by the persisted read, when it must fail. + /// Whether the persisted read returns a value, which can be . + private void StubArtistReads(ArtistEntity artist, ArtistEntity? persistedArtist = null, Error? error = null, bool hasPersistedArtist = false) + { + Queue> readResults = new(); + readResults.Enqueue(Result.From(artist)); + if (error is not null) + readResults.Enqueue(error); + else if (hasPersistedArtist) + readResults.Enqueue(Result.From(persistedArtist)); + else + readResults.Enqueue(Result.From(persistedArtist ?? artist)); + + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(_ => readResults.Dequeue()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidatorTests.cs new file mode 100644 index 00000000..6db619ee --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidatorTests.cs @@ -0,0 +1,2896 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +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 System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCommandValidatorTests +{ + private readonly UpdateArtistCommandFixture _updateArtistCommandFixture = new(); + private readonly UpdateArtistCommandValidator _validator = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeName: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name, which the not empty rule rejects + public void Validate_WhenNameIsEmpty_ShouldHaveValidationError(string name) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(name: name); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(name: new Faker().Random.String2(256)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(name: new Faker().Random.String2(255)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteExceeds2048Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(website: new Faker().Random.String2(2049)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeWebsite: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(website: new Faker().Internet.Url()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(musicBrainzArtistId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeMusicBrainzArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(musicBrainzArtistId: Guid.NewGuid()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeContributors: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeAlbums: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(albumId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeAlbumId: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(albumId: Guid.NewGuid())]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMetadata: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumTitleIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTitle: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty title + [InlineData(" ")] // whitespace title, which the not empty rule rejects + public void Validate_WhenAlbumTitleIsEmpty_ShouldHaveValidationError(string title) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: title))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalTitle: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeDescription: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: (MusicReleaseType)999))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseType: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: MusicReleaseType.Album))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseStatus: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Theory] + [InlineData(0)] // zero is not a valid total discs value + [InlineData(-1)] // a negative total discs value is not valid + public void Validate_WhenAlbumTotalDiscsIsNotPositive_ShouldHaveValidationError(int totalDiscs) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: totalDiscs))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalDiscsIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalDiscs: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid total tracks value + [InlineData(-1)] // a negative total tracks value is not valid + public void Validate_WhenAlbumTotalTracksIsNotPositive_ShouldHaveValidationError(int totalTracks) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: totalTracks))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalTracksIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalTracks: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseInfo: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReleaseVersionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenAlbumReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenAlbumReReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenAlbumReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenAlbumReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenAlbumGenresIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeGenres: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumGenreNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumGenresAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumTagsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTags: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumTagNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumTagsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeLanguage: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalLanguage: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumMediaFormatIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(mediaFormat: (MusicMediaFormat)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenAlbumMediaFormatIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenAlbumMediaFormatIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(mediaFormat: MusicMediaFormat.CD)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenAlbumCatalogNumberExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(51))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumCatalogNumberIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumBarcodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: string.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Theory] + [InlineData("123")] // too short to be a barcode + [InlineData("abcdefghijkl")] // not numeric + [InlineData("12345678901234")] // too long to be a barcode + public void Validate_WhenAlbumBarcodeHasInvalidFormat_ShouldHaveValidationError(string barcode) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: barcode)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Theory] + [InlineData("123456789012")] // 12 digit barcode + [InlineData("1234567890123")] // 13 digit barcode + public void Validate_WhenAlbumBarcodeIsValid_ShouldNotHaveValidationError(string barcode) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: barcode)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Fact] + public void Validate_WhenAlbumBarcodeIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseGroupIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseGroupId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseArtistIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseArtistId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzIdsAreNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseId: Guid.NewGuid(), musicBrainzReleaseGroupId: Guid.NewGuid(), musicBrainzReleaseArtistId: Guid.NewGuid())]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeContributors: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeRatings: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenAlbumRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(includeValue: false, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenAlbumRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingMaxValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, includeMaxValue: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumTracksIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeTracks: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TracksListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create()])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackId: Guid.NewGuid())])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackPathIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includePath: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty path + [InlineData(" ")] // whitespace path, which the not empty rule rejects + public void Validate_WhenTrackPathIsEmpty_ShouldHaveValidationError(string path) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: path)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackPathExceeds2048Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".flac")])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenTrackPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2000) + ".flac")])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeMetadata: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackTitleIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenTrackReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReleaseVersionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2019, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenTrackReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenTrackReReleaseDateIsBeforeOriginalReleaseDate_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), reReleaseDate: new DateOnly(2000, 1, 1))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenTrackGenresIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackGenreNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackTagsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackTagNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzRecordingIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzTrackIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzTrackId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeTrackNumber: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid track number + [InlineData(-1)] // a negative track number is not valid + public void Validate_WhenTrackNumberIsNotPositive_ShouldHaveValidationError(int trackNumber) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackNumber: trackNumber)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid disc number + [InlineData(-1)] // a negative disc number is not valid + public void Validate_WhenDiscNumberIsNotPositive_ShouldHaveValidationError(int discNumber) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(discNumber: discNumber)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackScriptExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(script: new Faker().Random.String2(51))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackKeyIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(key: (MusicKey)999)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Theory] + [InlineData(0)] // zero is not a valid tempo + [InlineData(-1)] // a negative tempo is not valid + public void Validate_WhenTrackBpmIsNotPositive_ShouldHaveValidationError(int bpm) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(bpm: bpm)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackWorkExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(256))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMoodNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(includeName: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIsrcValueIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(includeValue: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeContributors: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenTrackRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeRatings: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenTrackRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenTrackRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReleaseVersionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumCatalogNumberIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(50))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReleaseVersionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2020, 1, 1), originalReleaseYear: 2020, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenTrackReReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenTrackReReleaseDateIsAfterOriginalReleaseDate_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), reReleaseDate: new DateOnly(2001, 1, 1))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenTrackGenresAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackTagsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.NewGuid(), musicBrainzTrackId: Guid.NewGuid(), musicBrainzWorkId: Guid.NewGuid())])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackNumber: 7)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(discNumber: 1)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackScriptIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackScriptIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(script: new Faker().Random.String2(50))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackKeyIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + public void Validate_WhenTrackKeyIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(key: MusicKey.CMajor)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + public void Validate_WhenTrackBpmIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackBpmIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(bpm: 120)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackWorkIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackWorkIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(255))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMoodNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(name: "dramatic")])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackMoodsIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIsrcValueIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: "GBUM71029604")])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIsrcsIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeDiscNumber: false, includeScript: false, includeKey: false, includeBpm: false, includeWork: false, includeMusicBrainzRecordingId: false, includeMusicBrainzTrackId: false, includeMusicBrainzWorkId: false, includeMoods: false, includeIsrcs: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenTrackRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandlerTests.cs new file mode 100644 index 00000000..51d67bb7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandlerTests.cs @@ -0,0 +1,202 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetArtistQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly GetArtistQueryFixture _getArtistQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistQueryHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetArtistQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenArtistExists_ShouldReturnMappedArtistResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: true, includeContributors: true); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(artistId, result.Value.Id); + Assert.Equal(libraryId, result.Value.LibraryId); + Assert.Equal(artist.Name, result.Value.Name); + Assert.Equal(artist.Website, result.Value.Website); + Assert.NotNull(result.Value.Albums); + Assert.Equal(artist.Albums.Count, result.Value.Albums!.Count); + Assert.NotNull(result.Value.Contributors); + Assert.Equal(artist.Contributors.Count, result.Value.Contributors!.Count); + await _mockArtistRepository.Received(1).GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutEvaluatingThePolicy() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: Guid.NewGuid()); + GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.ToString()); + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId); + GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.ArtistIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidatorTests.cs new file mode 100644 index 00000000..edd39458 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidatorTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistQueryValidatorTests +{ + private readonly GetArtistQueryFixture _getArtistQueryFixture = new(); + private readonly GetArtistQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandlerTests.cs new file mode 100644 index 00000000..0a0281eb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandlerTests.cs @@ -0,0 +1,228 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetArtistAlbumsQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly GetArtistAlbumsQueryFixture _getArtistAlbumsQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsQueryHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetArtistAlbumsQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenArtistExists_ShouldReturnMappedAlbums() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + List albums = _albumEntityFixture.CreateMany(2); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(Result.From>(albums)); + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(albums.Count, result.Value.Count); + Assert.Equal(albums[0].Id, result.Value[0].Id); + Assert.Equal(albums[1].Id, result.Value[1].Id); + await _mockAlbumRepository.Received(1).GetByArtistIdAsync(artistId, Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutReadingAlbums() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false); + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.ToString()); + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.ArtistIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidatorTests.cs new file mode 100644 index 00000000..2f7316d5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidatorTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsQueryValidatorTests +{ + private readonly GetArtistAlbumsQueryFixture _getArtistAlbumsQueryFixture = new(); + private readonly GetArtistAlbumsQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandlerTests.cs new file mode 100644 index 00000000..d97d5385 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandlerTests.cs @@ -0,0 +1,262 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetArtistAlbumsLiteQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumLiteRowFixture _albumLiteRowFixture = new(); + private readonly GetArtistAlbumsLiteQueryFixture _getArtistAlbumsLiteQueryFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsLiteQueryHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetArtistAlbumsLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenArtistExists_ShouldReturnMappedPaginatedAlbumLiteResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + List albumLiteRows = _albumLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedAlbums = _paginatedResultDtoFixture.Create(data: albumLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAlbumRepository.GetAlbumsLiteByArtistIdAsync(artistId, Arg.Any(), Arg.Any()) + .Returns(Result.From(paginatedAlbums)); + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(albumLiteRows.Count, result.Value.Data.Count); + Assert.Equal(albumLiteRows[0].Id, result.Value.Data[0].Id); + Assert.Equal(albumLiteRows[0].Title, result.Value.Data[0].Title); + Assert.Equal(albumLiteRows[0].TotalTracks, result.Value.Data[0].TotalTracks); + Assert.Equal(paginatedAlbums.CurrentPage, result.Value.CurrentPage); + Assert.Equal(paginatedAlbums.PerPage, result.Value.PerPage); + Assert.Equal(paginatedAlbums.Count, result.Value.Count); + Assert.Equal(paginatedAlbums.NumberOfPages, result.Value.NumberOfPages); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldForwardTheArtistIdAndPaginationToTheRepository() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + PaginatedResultDto paginatedAlbums = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAlbumRepository.GetAlbumsLiteByArtistIdAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(paginatedAlbums)); + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockAlbumRepository.Received(1).GetAlbumsLiteByArtistIdAsync( + artistId, + Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && + paginationData.PerPage == query.PaginationData.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutReadingAlbums() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false); + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.ToString()); + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAlbumRepository.GetAlbumsLiteByArtistIdAsync(artistId, Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.ArtistIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidatorTests.cs new file mode 100644 index 00000000..7b52c0d9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidatorTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteQueryValidatorTests +{ + private readonly GetArtistAlbumsLiteQueryFixture _getArtistAlbumsLiteQueryFixture = new(); + private readonly GetArtistAlbumsLiteQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandlerTests.cs new file mode 100644 index 00000000..35b0e318 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandlerTests.cs @@ -0,0 +1,255 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetArtistsQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly GetArtistsQueryFixture _getArtistsQueryFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistsQueryHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetArtistsQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnMappedPaginatedResponses() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + List artistEntities = _artistEntityFixture.CreateMany(2); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: artistEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); + _mockArtistRepository.GetAllAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + shouldTrackEntities: false, + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(artistEntities.Count, result.Value.Data.Count); + Assert.Equal(paginatedArtists.CurrentPage, result.Value.CurrentPage); + Assert.Equal(paginatedArtists.PerPage, result.Value.PerPage); + Assert.Equal(paginatedArtists.Count, result.Value.Count); + Assert.Equal(paginatedArtists.NumberOfPages, result.Value.NumberOfPages); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsEmptyPage_ShouldReturnEmptyPaginatedResponses() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + shouldTrackEntities: false, + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.Data); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + _mockArtistRepository.GetAllAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + shouldTrackEntities: false, + cancellationToken: Arg.Any()) + .Returns(Errors.Library.FilterMustIncludeLibraryId); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldQueryRepositoryWithMappedFilterPaginationAndSearchTerm() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: libraryId.ToString(), searchTerm: "Queen"); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + shouldTrackEntities: false, + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockArtistRepository.Received(1).GetAllAsync( + Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage), + Arg.Any(), + Arg.Any(), + Arg.Is(filter => filter.LibraryId == libraryId && filter.SearchTerm == "Queen"), + shouldTrackEntities: false, + cancellationToken: Arg.Is(cancellationToken)); + } + + [Fact] + public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: libraryId.ToString(), includePaginationData: false, searchTerm: "Queen"); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + shouldTrackEntities: false, + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + await _mockArtistRepository.Received(1).GetAllAsync( + Arg.Is(paginationData => paginationData == null), + Arg.Any(), + Arg.Any(), + Arg.Is(filter => filter.LibraryId == libraryId && filter.SearchTerm == "Queen"), + shouldTrackEntities: false, + cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: libraryId.ToString()); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidatorTests.cs new file mode 100644 index 00000000..a9f6b450 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidatorTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsQueryValidatorTests +{ + private readonly GetArtistsQueryFixture _getArtistsQueryFixture = new(); + private readonly GetArtistsQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandlerTests.cs new file mode 100644 index 00000000..1b4f19bb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandlerTests.cs @@ -0,0 +1,250 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +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.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetArtistsLiteQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistLiteRowFixture _artistLiteRowFixture = new(); + private readonly GetArtistsLiteQueryFixture _getArtistsLiteQueryFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistsLiteQueryHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetArtistsLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnMappedPaginatedResponses() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + List artistLiteRows = _artistLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: artistLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); + _mockArtistRepository.GetAllLiteAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(artistLiteRows.Count, result.Value.Data.Count); + Assert.Equal(artistLiteRows[0].Id, result.Value.Data[0].Id); + Assert.Equal(artistLiteRows[0].Name, result.Value.Data[0].Name); + Assert.Equal(paginatedArtists.CurrentPage, result.Value.CurrentPage); + Assert.Equal(paginatedArtists.PerPage, result.Value.PerPage); + Assert.Equal(paginatedArtists.Count, result.Value.Count); + Assert.Equal(paginatedArtists.NumberOfPages, result.Value.NumberOfPages); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsEmptyPage_ShouldReturnEmptyPaginatedResponses() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllLiteAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.Data); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + _mockArtistRepository.GetAllLiteAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + cancellationToken: Arg.Any()) + .Returns(Errors.Library.FilterMustIncludeLibraryId); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldQueryRepositoryWithMappedFilterPaginationAndSearchTerm() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: libraryId.ToString(), searchTerm: "Queen"); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllLiteAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockArtistRepository.Received(1).GetAllLiteAsync( + Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage), + Arg.Any(), + Arg.Any(), + Arg.Is(filter => filter.LibraryId == libraryId && filter.SearchTerm == "Queen"), + cancellationToken: Arg.Is(cancellationToken)); + } + + [Fact] + public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: libraryId.ToString(), includePaginationData: false, searchTerm: "Queen"); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllLiteAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + await _mockArtistRepository.Received(1).GetAllLiteAsync( + Arg.Is(paginationData => paginationData == null), + Arg.Any(), + Arg.Any(), + Arg.Is(filter => filter.LibraryId == libraryId && filter.SearchTerm == "Queen"), + cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: libraryId.ToString()); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidatorTests.cs new file mode 100644 index 00000000..a2335d28 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidatorTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteQueryValidatorTests +{ + private readonly GetArtistsLiteQueryFixture _getArtistsLiteQueryFixture = new(); + private readonly GetArtistsLiteQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/ArtistConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/ArtistConfigurationTests.cs new file mode 100644 index 00000000..f18fc3f6 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/ArtistConfigurationTests.cs @@ -0,0 +1,135 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistConfigurationTests : IDisposable +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public ArtistConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Artists", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotGenerateTheIdValue() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(ArtistEntity.Id)); + + // Assert + Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!; + + // Act + IProperty libraryIdProperty = entityType.GetProperty(nameof(ArtistEntity.LibraryId)); + IProperty nameProperty = entityType.GetProperty(nameof(ArtistEntity.Name)); + IProperty websiteProperty = entityType.GetProperty(nameof(ArtistEntity.Website)); + IProperty musicBrainzArtistIdProperty = entityType.GetProperty(nameof(ArtistEntity.MusicBrainzArtistId)); + + // Assert + Assert.False(libraryIdProperty.IsNullable); + Assert.False(nameProperty.IsNullable); + Assert.Equal(255, nameProperty.GetMaxLength()); + Assert.True(websiteProperty.IsNullable); + Assert.Equal(2048, websiteProperty.GetMaxLength()); + Assert.True(musicBrainzArtistIdProperty.IsNullable); + Assert.Equal(typeof(Guid?), musicBrainzArtistIdProperty.ClrType); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureContributorsRelationshipWithCascadeDelete() + { + // Arrange + IEntityType contributorEntityType = _context.Model.FindEntityType(typeof(ArtistContributorEntity))!; + + // Act + List foreignKeys = [.. contributorEntityType.GetForeignKeys()]; + + // Assert + IForeignKey artistForeignKey = Assert.Single(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(ArtistEntity)); + Assert.Equal(nameof(ArtistContributorEntity.ArtistId), artistForeignKey.Properties.Single().Name); + Assert.Equal(DeleteBehavior.Cascade, artistForeignKey.DeleteBehavior); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnLibraryIdAndName() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + IIndex uniquenessIndex = Assert.Single(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(ArtistEntity.LibraryId), nameof(ArtistEntity.Name)])); + Assert.True(uniquenessIndex.IsUnique); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(ArtistEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(ArtistEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(ArtistEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(ArtistEntity.UpdatedBy)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.False(createdByProperty.IsNullable); + Assert.True(updatedOnUtcProperty.IsNullable); + Assert.True(updatedByProperty.IsNullable); + } + + /// + /// Disposes the database context. + /// + public void Dispose() + { + _context.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs new file mode 100644 index 00000000..add56a0c --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs @@ -0,0 +1,1146 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +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.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.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.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly AlbumRepository _albumRepository; + private readonly TrackRepository _trackRepository; + private readonly ArtistRepository _sut; + 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(); + private readonly BaseFilterDtoFixture _baseFilterDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ArtistRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _trackRepository = new TrackRepository(_mockContext); + _albumRepository = new AlbumRepository(_mockContext, _trackRepository); + _sut = new ArtistRepository(_mockContext, _albumRepository, _trackRepository); + } + + [Fact] + public async Task InsertAsync_WhenArtistDoesNotExist_ShouldAddArtistToContextAndReturnCreated() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedArtist = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + Assert.NotNull(addedArtist); + } + + [Fact] + public async Task InsertAsync_WhenArtistWithTheSameIdAlreadyExists_ShouldReturnArtistAlreadyExists() + { + // Arrange + ArtistEntity existingArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(existingArtist); + await _mockContext.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); + Assert.Single(_mockContext.ChangeTracker.Entries()); // Only the existing artist should remain tracked. + } + + [Fact] + public async Task InsertAsync_WhenAnotherArtistOfTheSameLibraryHasTheSameName_ShouldReturnArtistAlreadyExists() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(existingArtist); + await _mockContext.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_ShouldAddArtistToContextAndReturnCreated() + { + // Arrange + ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: Guid.NewGuid(), name: "Queen", includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(existingArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(libraryId: Guid.NewGuid(), name: "Queen", includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // An artist only has to be unique within its own library, so the second library is allowed to register the same name. + Assert.Contains(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + } + + [Fact] + public async Task InsertAsync_WhenTwoTracksOfTheSameRequestShareAPath_ShouldReturnTrackAlreadyExists() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity firstTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false); + TrackEntity secondTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false); + album.Tracks = [firstTrack, secondTrack]; + artist.Albums = [album]; + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + // The duplicate within the request is detected before anything is written. + Assert.Empty(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task InsertAsync_WhenATrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: Guid.NewGuid(), libraryId: libraryId, includeTracks: false, includeMetadata: false); + storedAlbum.Tracks = [_trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)]; + _mockContext.Albums.Add(storedAlbum); + await _mockContext.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/bohemian-rhapsody.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); + Assert.Empty(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldAddArtistToContextAndReturnCreated() + { + // Arrange + 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/we-will-rock-you.flac", includeMetadata: false)]; + artist.Albums = [album]; + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // The same physical path is only unique within its library, so another library is allowed to register it. + Assert.Contains(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + } + + [Fact] + public async Task InsertAsync_WhenExistingTagAndGenreNamesAreFound_ShouldReplaceThemWithTheStoredInstancesAcrossAlbumsAndTracks() + { + // Arrange + TagEntity existingTag = _tagEntityFixture.Create(name: "ExistingTag"); + GenreEntity existingGenre = _genreEntityFixture.Create(name: "ExistingGenre"); + _mockContext.Set().Add(existingTag); + _mockContext.Set().Add(existingGenre); + await _mockContext.SaveChangesAsync(); + + 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: "ExistingTag"), _tagEntityFixture.Create(name: "NewAlbumTag")]; + album.Genres = [_genreEntityFixture.Create(name: "ExistingGenre"), _genreEntityFixture.Create(name: "NewAlbumGenre")]; + track.Tags = [_tagEntityFixture.Create(name: "ExistingTag"), _tagEntityFixture.Create(name: "NewTrackTag")]; + track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre"), _genreEntityFixture.Create(name: "NewTrackGenre")]; + album.Tracks = [track]; + artist.Albums = [album]; + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedArtist = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + Assert.NotNull(addedArtist); + AlbumEntity addedAlbum = Assert.Single(addedArtist!.Entity.Albums); + Assert.Contains(addedAlbum.Tags, tag => tag.Name == "ExistingTag" && ReferenceEquals(tag, existingTag)); + Assert.Contains(addedAlbum.Tags, tag => tag.Name == "NewAlbumTag" && !ReferenceEquals(tag, existingTag)); + Assert.Contains(addedAlbum.Genres, genre => genre.Name == "ExistingGenre" && ReferenceEquals(genre, existingGenre)); + Assert.Contains(addedAlbum.Genres, genre => genre.Name == "NewAlbumGenre" && !ReferenceEquals(genre, existingGenre)); + TrackEntity addedTrack = Assert.Single(addedAlbum.Tracks); + Assert.Contains(addedTrack.Tags, tag => tag.Name == "ExistingTag" && ReferenceEquals(tag, existingTag)); + Assert.Contains(addedTrack.Tags, tag => tag.Name == "NewTrackTag" && !ReferenceEquals(tag, existingTag)); + Assert.Contains(addedTrack.Genres, genre => genre.Name == "ExistingGenre" && ReferenceEquals(genre, existingGenre)); + Assert.Contains(addedTrack.Genres, genre => genre.Name == "NewTrackGenre" && !ReferenceEquals(genre, existingGenre)); + // The shared rows are reused instead of being duplicated. + Assert.Single(_mockContext.Set().Where(tag => tag.Name == "ExistingTag")); + Assert.Single(_mockContext.Set().Where(genre => genre.Name == "ExistingGenre")); + } + + [Fact] + public async Task InsertAsync_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTracks_ShouldTrackASingleInstancePerName() + { + // Arrange + 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); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // The name shared by the album and its tracks is represented by a single tracked instance, so the same key is never tracked twice. + EntityEntry addedTag = Assert.Single(_mockContext.ChangeTracker.Entries(), entry => entry.Entity.Name == "SharedNewTag"); + EntityEntry addedGenre = Assert.Single(_mockContext.ChangeTracker.Entries(), entry => entry.Entity.Name == "SharedNewGenre"); + Assert.True(ReferenceEquals(album.Tags.Single(tag => tag.Name == "SharedNewTag"), addedTag.Entity)); + Assert.True(ReferenceEquals(track.Tags.Single(tag => tag.Name == "SharedNewTag"), addedTag.Entity)); + Assert.True(ReferenceEquals(album.Genres.Single(genre => genre.Name == "SharedNewGenre"), addedGenre.Entity)); + Assert.True(ReferenceEquals(track.Genres.Single(genre => genre.Name == "SharedNewGenre"), addedGenre.Entity)); + } + + [Fact] + public async Task InsertAsync_WhenArtistHasNoTagsOrGenres_ShouldStillAddArtistAndReturnCreated() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: true, includeContributors: false, includeMetadata: false); + AlbumEntity album = Assert.Single(artist.Albums); + album.Tags = []; + album.Genres = []; + album.Tracks[0].Tags = []; + album.Tracks[0].Genres = []; + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedArtist = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + Assert.NotNull(addedArtist); + Assert.Empty(addedArtist!.Entity.Albums[0].Tags); + Assert.Empty(addedArtist.Entity.Albums[0].Genres); + } + + [Fact] + public async Task UpdateAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFound() + { + // Arrange + ArtistEntity data = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenArtistExists_ShouldUpdateItsScalarProperties() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Name = "Freddie Mercury"; + data.Website = "https://www.queenonline.com"; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + ArtistEntity? retrievedArtist = await _mockContext.Artists.FindAsync(storedArtist.Id); + Assert.NotNull(retrievedArtist); + Assert.Equal("Freddie Mercury", retrievedArtist!.Name); + Assert.Equal("https://www.queenonline.com", retrievedArtist.Website); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingLibraryIdDiffers_ShouldPreserveTheStoredLibraryId() + { + // Arrange + Guid storedLibraryId = Guid.NewGuid(); + ArtistEntity storedArtist = _artistEntityFixture.Create(libraryId: storedLibraryId, includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.LibraryId = Guid.NewGuid(); + data.Name = "Queen"; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity? retrievedArtist = await _mockContext.Artists.FindAsync(storedArtist.Id); + Assert.NotNull(retrievedArtist); + Assert.Equal(storedLibraryId, retrievedArtist!.LibraryId); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingAuditColumnsDiffer_ShouldPreserveTheStoredAuditColumns() + { + // Arrange + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + storedArtist.CreatedOnUtc = storedCreatedOnUtc; + storedArtist.CreatedBy = storedCreatedBy; + storedArtist.UpdatedOnUtc = null; + storedArtist.UpdatedBy = null; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Name = "Freddie"; + data.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + data.CreatedBy = Guid.NewGuid(); + data.UpdatedOnUtc = DateTime.UtcNow; + data.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity? retrievedArtist = await _mockContext.Artists.FindAsync(storedArtist.Id); + Assert.NotNull(retrievedArtist); + Assert.Equal("Freddie", retrievedArtist!.Name); + // The audit columns are owned by the auditing interceptor alone, so an edit never overwrites them. + Assert.Equal(storedCreatedOnUtc, retrievedArtist.CreatedOnUtc); + Assert.Equal(storedCreatedBy, retrievedArtist.CreatedBy); + Assert.Null(retrievedArtist.UpdatedOnUtc); + Assert.Null(retrievedArtist.UpdatedBy); + } + + [Fact] + public async Task UpdateAsync_WhenAnUnchangedContributorIsSubmitted_ShouldPreserveItsStoredIdentityAndAuditColumns() + { + // Arrange + Guid keptMediaContributorId = Guid.NewGuid(); + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + ArtistContributorEntity keptContributor = _artistContributorEntityFixture.Create( + artistId: storedArtist.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer); + storedArtist.Contributors = [keptContributor]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + Guid keptContributorId = keptContributor.Id; + DateTime keptContributorCreatedOnUtc = keptContributor.CreatedOnUtc; + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Contributors = + [_artistContributorEntityFixture.Create(artistId: storedArtist.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer)]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistContributorEntity storedContributor = Assert.Single( + await _mockContext.Set().Where(contributor => contributor.ArtistId == storedArtist.Id).ToListAsync()); + Assert.Equal(keptContributorId, storedContributor.Id); + Assert.Equal(keptContributorCreatedOnUtc, storedContributor.CreatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenContributorsChange_ShouldDeleteTheRemovedAndInsertTheAddedOnes() + { + // Arrange + Guid keptMediaContributorId = Guid.NewGuid(); + Guid removedMediaContributorId = Guid.NewGuid(); + Guid addedMediaContributorId = Guid.NewGuid(); + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + ArtistContributorEntity keptContributor = _artistContributorEntityFixture.Create( + artistId: storedArtist.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer); + ArtistContributorEntity removedContributor = _artistContributorEntityFixture.Create( + artistId: storedArtist.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Composer); + storedArtist.Contributors = [keptContributor, removedContributor]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + Guid keptContributorId = keptContributor.Id; + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Contributors = + [ + _artistContributorEntityFixture.Create(artistId: storedArtist.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer), + _artistContributorEntityFixture.Create(artistId: storedArtist.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals) + ]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await _mockContext.Set() + .Where(contributor => contributor.ArtistId == storedArtist.Id) + .ToListAsync(); + Assert.Equal(2, storedContributors.Count); + // The unchanged participation keeps its identity, while only the delta is deleted and inserted. + Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id); + Assert.DoesNotContain(storedContributors, contributor => contributor.MediaContributorId == removedMediaContributorId); + Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId); + } + + [Fact] + public async Task UpdateAsync_WhenAlbumsChange_ShouldInsertTheAddedUpdateTheExistingAndRemoveTheMissingOnes() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity updatedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + AlbumEntity removedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + storedArtist.Albums = [updatedAlbum, removedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + AlbumEntity incomingUpdatedAlbum = _albumEntityFixture.Create(id: updatedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + AlbumEntity incomingAddedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingUpdatedAlbum, incomingAddedAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedAlbums = await _mockContext.Albums.ToListAsync(); + Assert.Contains(storedAlbums, album => album.Id == updatedAlbum.Id); + Assert.Contains(storedAlbums, album => album.Id == incomingAddedAlbum.Id); + Assert.DoesNotContain(storedAlbums, album => album.Id == removedAlbum.Id); + } + + [Fact] + public async Task UpdateAsync_WhenTwoNewTracksOfTheRequestShareAPath_ShouldReturnTrackAlreadyExistsBeforeWriting() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + storedAlbum.Tracks = [_trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false)]; + storedArtist.Albums = [storedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: storedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + incomingAlbum.Tracks = + [ + _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false), + _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false) + ]; + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + // The unique path is checked for the whole request before any album or track is written. + Assert.DoesNotContain(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added); + Assert.DoesNotContain(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added); + } + + [Fact] + public async Task UpdateAsync_WhenANewTrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExistsBeforeWriting() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + storedAlbum.Tracks = [_trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)]; + storedArtist.Albums = [storedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: storedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + incomingAlbum.Tracks = [_trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)]; + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + Assert.DoesNotContain(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added); + Assert.DoesNotContain(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added); + } + + [Fact] + public async Task UpdateAsync_WhenTracksChangeWithinAnAlbum_ShouldInsertTheAddedUpdateTheExistingAndRemoveTheMissingOnes() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity keptTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false); + TrackEntity removedTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false); + storedAlbum.Tracks = [keptTrack, removedTrack]; + storedArtist.Albums = [storedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + TrackEntity incomingKeptTrack = _trackEntityFixture.Create(id: keptTrack.Id, albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false); + incomingKeptTrack.Title = "Somebody to Love"; + TrackEntity incomingAddedTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false); + AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: storedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + incomingAlbum.Tracks = [incomingKeptTrack, incomingAddedTrack]; + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedTracks = await _mockContext.Tracks.ToListAsync(); + Assert.Contains(storedTracks, track => track.Id == keptTrack.Id); + Assert.Contains(storedTracks, track => track.Id == incomingAddedTrack.Id); + Assert.DoesNotContain(storedTracks, track => track.Id == removedTrack.Id); + Assert.Equal("Somebody to Love", storedTracks.Single(track => track.Id == keptTrack.Id).Title); + } + + [Fact] + public async Task GetByIdAsync_WhenArtistExists_ShouldReturnTheArtist() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(artist.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(artist.Id, result.Value!.Id); + } + + [Fact] + public async Task GetByIdAsync_WhenArtistDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenNavigationPropertiesAreIncluded_ShouldPopulateTheRelatedCollections() + { + // Arrange + ArtistEntity artist = CreateArtistWithFullAggregate(); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // 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.Tags.Count); + 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 DeleteByIdAsync_WhenArtistExists_ShouldRemoveItAndReturnDeleted() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByIdAsync(artist.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + Assert.Contains(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Deleted && entry.Entity.Id == artist.Id); + await _mockContext.SaveChangesAsync(); + Assert.DoesNotContain(await _mockContext.Artists.ToListAsync(), candidate => candidate.Id == artist.Id); + } + + [Fact] + public async Task DeleteByIdAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFound() + { + // Act + Result result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task GetAllAsync_WhenFilterIsNotALibraryFilter_ShouldReturnFilterMustIncludeLibraryId() + { + // Arrange + BaseFilterDto filter = _baseFilterDtoFixture.Create(); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnFilterMustIncludeLibraryId() + { + // Arrange + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllAsync_WhenCalled_ShouldReturnOnlyTheArtistsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity firstArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity secondArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity artistOfAnotherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(firstArtist, secondArtist, artistOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.All(result.Value.Data, artist => Assert.Equal(libraryId, artist.LibraryId)); + Assert.DoesNotContain(result.Value.Data, artist => artist.Id == artistOfAnotherLibrary.Id); + } + + [Theory] + [InlineData("Queens")] // The search term matches the stored casing. + [InlineData("queens")] // The search term is entirely lower case. + [InlineData("QUEENS")] // The search term is entirely upper case. + public async Task GetAllAsync_WhenSearchTermProvided_ShouldMatchTheNameCaseInsensitively(string searchTerm) + { + // Arrange + 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); + _mockContext.Artists.AddRange(matchingArtist, otherArtist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: searchTerm); + + // 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_WhenCalled_ShouldOrderByNameThenById() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + ArtistEntity secondAlphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + ArtistEntity firstAlphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(betaArtist, secondAlphaArtist, firstAlphaArtist); + await _mockContext.SaveChangesAsync(); + + List seededArtists = [betaArtist, secondAlphaArtist, firstAlphaArtist]; + Guid[] expectedOrder = [.. seededArtists.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id).Select(artist => artist.Id)]; + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedOrder, result.Value.Data.Select(artist => artist.Id)); + } + + [Fact] + public async Task GetAllAsync_WhenSortOrderIsDescending_ShouldOrderByNameDescendingThenById() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity alphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(alphaArtist, betaArtist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, null, SortOrder.Descending, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([betaArtist.Id, alphaArtist.Id], result.Value.Data.Select(artist => artist.Id)); + } + + [Theory] + [InlineData("website", SortOrder.Ascending)] // the website field, ascending + [InlineData("website", SortOrder.Descending)] // the website field, descending + [InlineData("musicbrainzartistid", SortOrder.Ascending)] // the MusicBrainz artist Id field, ascending + [InlineData("musicbrainzartistid", SortOrder.Descending)] // the MusicBrainz artist Id field, descending + [InlineData("createdonutc", SortOrder.Ascending)] // the creation timestamp field, ascending + [InlineData("createdonutc", SortOrder.Descending)] // the creation timestamp field, descending + [InlineData("updatedonutc", SortOrder.Ascending)] // the update timestamp field, ascending + [InlineData("updatedonutc", SortOrder.Descending)] // the update timestamp field, descending + public async Task GetAllAsync_WhenSortedByField_ShouldOrderByFieldThenById(string sortBy, SortOrder sortOrder) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity secondArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Second", includeAlbums: false, includeContributors: false); + ArtistEntity firstArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "First", includeAlbums: false, includeContributors: false); + // The two seeded artists carry a smaller value for every sortable field, so each sort key has a deterministic expected order. + firstArtist.Website = "https://a.example.com"; + secondArtist.Website = "https://b.example.com"; + firstArtist.MusicBrainzArtistId = Guid.Parse("00000000-0000-0000-0000-000000000001"); + secondArtist.MusicBrainzArtistId = Guid.Parse("00000000-0000-0000-0000-000000000002"); + firstArtist.CreatedOnUtc = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + secondArtist.CreatedOnUtc = new DateTime(2024, 1, 2, 0, 0, 0, DateTimeKind.Utc); + firstArtist.UpdatedOnUtc = new DateTime(2024, 2, 1, 0, 0, 0, DateTimeKind.Utc); + secondArtist.UpdatedOnUtc = new DateTime(2024, 2, 2, 0, 0, 0, DateTimeKind.Utc); + _mockContext.Artists.AddRange(secondArtist, firstArtist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, sortBy, sortOrder, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Guid[] expectedOrder = sortOrder == SortOrder.Descending + ? [secondArtist.Id, firstArtist.Id] + : [firstArtist.Id, secondArtist.Id]; + Assert.Equal(expectedOrder, result.Value.Data.Select(artist => artist.Id)); + } + + [Fact] + public async Task GetAllAsync_WhenPaginationDataIsNull_ShouldReturnAllArtistsWithExpectedMetadata() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List artists = _artistEntityFixture.CreateMany(3); + foreach (ArtistEntity artist in artists) + artist.LibraryId = libraryId; + _mockContext.Artists.AddRange(artists); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(3, page.Count); + Assert.Equal(3, page.Data.Count); + Assert.Equal(1, page.CurrentPage); + Assert.Equal(3, page.PerPage); + Assert.Equal(1, page.NumberOfPages); + } + + [Theory] + [InlineData(1, 2, 1, 2)] // The first page is fully returned. + [InlineData(2, 2, 2, 2)] // A middle page is fully returned. + [InlineData(3, 2, 3, 1)] // The last page is partially returned. + [InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page. + public async Task GetAllAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List artists = _artistEntityFixture.CreateMany(5); + foreach (ArtistEntity artist in artists) + artist.LibraryId = libraryId; + _mockContext.Artists.AddRange(artists); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(5, page.Count); + Assert.Equal(3, page.NumberOfPages); + Assert.Equal(expectedCurrentPage, page.CurrentPage); + Assert.Equal(perPage, page.PerPage); + Assert.Equal(expectedRowCount, page.Data.Count); + } + + [Fact] + public async Task GetAllAsync_WhenNavigationPropertiesAreIncluded_ShouldPopulateTheRelatedCollections() + { + // Arrange + ArtistEntity artist = CreateArtistWithFullAggregate(); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: artist.LibraryId); + + // 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.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.Moods.Count); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetAllLiteAsync_WhenFilterIsNotALibraryFilter_ShouldReturnFilterMustIncludeLibraryId() + { + // Arrange + BaseFilterDto filter = _baseFilterDtoFixture.Create(); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllLiteAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnFilterMustIncludeLibraryId() + { + // Arrange + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllLiteAsync_WhenCalled_ShouldReturnOnlyTheArtistsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artistOfLibrary = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity artistOfAnotherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(artistOfLibrary, artistOfAnotherLibrary); + await _mockContext.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); + ArtistLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(artistOfLibrary.Id, row.Id); + Assert.Equal(1, result.Value.Count); + } + + [Theory] + [InlineData("Queens")] // The search term matches the stored casing. + [InlineData("queens")] // The search term is entirely lower case. + [InlineData("QUEENS")] // The search term is entirely upper case. + public async Task GetAllLiteAsync_WhenSearchTermProvided_ShouldMatchTheNameCaseInsensitively(string searchTerm) + { + // Arrange + 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); + _mockContext.Artists.AddRange(matchingArtist, otherArtist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: searchTerm); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(matchingArtist.Id, row.Id); + } + + [Fact] + public async Task GetAllLiteAsync_WhenCalled_ShouldOrderByNameThenById() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + ArtistEntity secondAlphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + ArtistEntity firstAlphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(betaArtist, secondAlphaArtist, firstAlphaArtist); + await _mockContext.SaveChangesAsync(); + + List seededArtists = [betaArtist, secondAlphaArtist, firstAlphaArtist]; + Guid[] expectedOrder = [.. seededArtists.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id).Select(artist => artist.Id)]; + 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(expectedOrder, result.Value.Data.Select(row => row.Id)); + } + + [Fact] + public async Task GetAllLiteAsync_WhenSortOrderIsDescending_ShouldOrderByNameDescendingThenById() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity alphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(alphaArtist, betaArtist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, SortOrder.Descending, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([betaArtist.Id, alphaArtist.Id], result.Value.Data.Select(artist => artist.Id)); + } + + [Fact] + public async Task GetAllLiteAsync_WhenCalled_ShouldProjectOnlyTheIdAndTheName() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(artist.Id, row.Id); + Assert.Equal("Queen", row.Name); + } + + [Fact] + public async Task GetAllLiteAsync_WhenPaginationDataIsNull_ShouldReturnAllArtistsWithExpectedMetadata() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List artists = _artistEntityFixture.CreateMany(3); + foreach (ArtistEntity artist in artists) + artist.LibraryId = libraryId; + _mockContext.Artists.AddRange(artists); + await _mockContext.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); + PaginatedResultDto page = result.Value; + Assert.Equal(3, page.Count); + Assert.Equal(3, page.Data.Count); + Assert.Equal(1, page.CurrentPage); + Assert.Equal(3, page.PerPage); + Assert.Equal(1, page.NumberOfPages); + } + + [Theory] + [InlineData(1, 2, 1, 2)] // The first page is fully returned. + [InlineData(2, 2, 2, 2)] // A middle page is fully returned. + [InlineData(3, 2, 3, 1)] // The last page is partially returned. + [InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page. + public async Task GetAllLiteAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List artists = _artistEntityFixture.CreateMany(5); + foreach (ArtistEntity artist in artists) + artist.LibraryId = libraryId; + _mockContext.Artists.AddRange(artists); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(5, page.Count); + Assert.Equal(3, page.NumberOfPages); + Assert.Equal(expectedCurrentPage, page.CurrentPage); + Assert.Equal(perPage, page.PerPage); + Assert.Equal(expectedRowCount, page.Data.Count); + } + + /// + /// Creates an artist that owns an album which in turn owns a track, with every related collection of the aggregate populated deterministically. + /// + /// The created artist. + private ArtistEntity CreateArtistWithFullAggregate() + { + ArtistEntity artist = _artistEntityFixture.Create(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: artist.LibraryId, includeTracks: false, includeMetadata: false); + album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + album.Tags = [_tagEntityFixture.Create(name: "AlbumTag1"), _tagEntityFixture.Create(name: "AlbumTag2")]; + album.Genres = [_genreEntityFixture.Create(name: "AlbumGenre1"), _genreEntityFixture.Create(name: "AlbumGenre2")]; + album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, includeMetadata: false); + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)]; + track.Tags = [_tagEntityFixture.Create(name: "TrackTag1"), _tagEntityFixture.Create(name: "TrackTag2")]; + track.Genres = [_genreEntityFixture.Create(name: "TrackGenre1"), _genreEntityFixture.Create(name: "TrackGenre2")]; + 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]; + return artist; + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/Specifications/ArtistSearchSpecificationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/Specifications/ArtistSearchSpecificationTests.cs new file mode 100644 index 00000000..cd3ddb0d --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/Specifications/ArtistSearchSpecificationTests.cs @@ -0,0 +1,111 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary.Specifications; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistSearchSpecificationTests +{ + private readonly ArtistEntityFixture _artistEntityFixture = new(); + + [Fact] + public void ToExpression_WhenNameContainsSearchTerm_ShouldMatchArtist() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false); + ArtistSearchSpecification specification = new("Stone"); + + // Act + bool result = specification.IsSatisfiedBy(artist); + + // Assert + Assert.True(result); + } + + [Fact] + public void ToExpression_WhenNameDoesNotContainSearchTerm_ShouldNotMatchArtist() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false); + ArtistSearchSpecification specification = new("Queen"); + + // Act + bool result = specification.IsSatisfiedBy(artist); + + // Assert + Assert.False(result); + } + + [Fact] + public void ToExpression_WhenNameMatchesInDifferentCase_ShouldMatchCaseInsensitively() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false); + ArtistSearchSpecification specification = new("QUEENS"); + + // Act + bool result = specification.IsSatisfiedBy(artist); + + // Assert + Assert.True(result); + } + + [Fact] + public void ToExpression_WhenSearchTermIsEmpty_ShouldMatchEveryArtist() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false); + ArtistSearchSpecification specification = new(string.Empty); + + // Act + bool result = specification.IsSatisfiedBy(artist); + + // Assert + // The repository guards blank terms with IsNullOrWhiteSpace before building the specification, so an empty term is documented as matching every artist rather than being treated as a literal. + Assert.True(result); + } + + [Fact] + public void ToExpression_WhenSearchTermIsWhitespace_ShouldNotMatchAnArtistWithoutThatWhitespace() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false); + ArtistSearchSpecification specification = new(" "); + + // Act + bool result = specification.IsSatisfiedBy(artist); + + // Assert + // A whitespace-only term is not silently ignored, it is matched literally. + Assert.False(result); + } + + [Fact] + public void ToExpression_WhenApplied_ShouldFilterOutNonMatchingArtists() + { + // Arrange + List artists = + [ + _artistEntityFixture.Create(name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false), + _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false), + _artistEntityFixture.Create(name: "Stone Temple Pilots", includeAlbums: false, includeContributors: false) + ]; + ArtistSearchSpecification specification = new("stone"); + + // Act + IEnumerable matchingArtists = artists.AsQueryable().Where(specification.ToExpression()); + + // Assert + Assert.Equal(2, matchingArtists.Count()); + Assert.DoesNotContain(matchingArtists, artist => artist.Name == "Radiohead"); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs index b8b80380..82eefad2 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs @@ -1,11 +1,23 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; @@ -19,6 +31,16 @@ public class ArtistTests private readonly ArtistFixture _artistFixture = new(); private readonly AlbumFixture _albumFixture = new(); private readonly TrackFixture _trackFixture = new(); + private readonly ArtistIdFixture _artistIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly AlbumMetadataFixture _albumMetadataFixture = new(); + private readonly BarcodeFixture _barcodeFixture = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); + private readonly AudioRatingFixture _audioRatingFixture = new(); + private readonly AudioMetadataFixture _audioMetadataFixture = new(); + private readonly MoodFixture _moodFixture = new(); + private readonly IsrcFixture _isrcFixture = new(); [Fact] public void AddTrackToAlbum_WhenAlbumIsOwnedByTheArtist_ShouldAddTheTrackAndReturnSuccess() @@ -72,4 +94,598 @@ public class ArtistTests Assert.Equal(Errors.Music.TheTrackIsAlreadyInTheAlbum, result.FirstError); Assert.Single(album.Tracks); } + + [Fact] + public void Create_WhenCalledWithValidData_ShouldCreateArtistWithAllProperties() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MusicBrainzId musicBrainzArtistId = _musicBrainzIdFixture.Create(); + List contributors = [_musicMediaContributorFixture.Create()]; + Album album = _albumFixture.Create(); + DateTime beforeCreate = DateTime.UtcNow; + + // Act + Result result = Artist.Create( + libraryId, + "Queen", + Optional.Some("https://www.queenonline.com"), + Optional.Some(musicBrainzArtistId), + contributors, + [album]); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.NotEqual(Guid.Empty, artist.Id.Value); + Assert.Equal(libraryId, artist.LibraryId); + Assert.Equal("Queen", artist.Name); + Assert.Equal(Optional.Some("https://www.queenonline.com"), artist.Website); + Assert.Equal(Optional.Some(musicBrainzArtistId), artist.MusicBrainzArtistId); + Assert.Equal(contributors, artist.Contributors); + Assert.Single(artist.Albums); + Assert.Equal(album, artist.Albums.Single()); + Assert.InRange(artist.CreatedOnUtc, beforeCreate, DateTime.UtcNow); + Assert.False(artist.UpdatedOnUtc.HasValue); + } + + [Fact] + public void Create_WhenOptionalValuesAreAbsent_ShouldCreateArtistWithoutThem() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Album album = _albumFixture.Create(); + + // Act + Result result = Artist.Create( + libraryId, + "Queen", + Optional.None(), + Optional.None(), + [], + [album]); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.False(artist.Website.HasValue); + Assert.False(artist.MusicBrainzArtistId.HasValue); + Assert.Empty(artist.Contributors); + Assert.Single(artist.Albums); + } + + [Theory] + [InlineData(null)] // null name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void Create_WhenNameIsNullOrWhitespace_ShouldReturnArtistNameCannotBeEmptyError(string? name) + { + // Act + Result result = Artist.Create( + _libraryIdFixture.Create(), + name!, + Optional.None(), + Optional.None(), + [], + [_albumFixture.Create()]); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Create_WhenAlbumsListIsEmpty_ShouldReturnArtistMustHaveAtLeastOneAlbumError() + { + // Act + Result result = Artist.Create( + _libraryIdFixture.Create(), + "Queen", + Optional.None(), + Optional.None(), + [], + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + } + + [Fact] + public void CreateWithId_WhenCalledWithValidData_ShouldPreserveIdentityAndTimestamps() + { + // Arrange + ArtistId artistId = _artistIdFixture.Create(); + LibraryId libraryId = _libraryIdFixture.Create(); + Album album = _albumFixture.Create(); + DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1); + DateTime updatedOnUtc = DateTime.UtcNow; + + // Act + Result result = Artist.Create( + artistId, + libraryId, + "Queen", + Optional.Some("https://www.queenonline.com"), + Optional.None(), + [], + [album], + createdOnUtc, + Optional.Some(updatedOnUtc)); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.Equal(artistId, artist.Id); + Assert.Equal(libraryId, artist.LibraryId); + Assert.Equal("Queen", artist.Name); + Assert.Equal(Optional.Some("https://www.queenonline.com"), artist.Website); + Assert.Equal(createdOnUtc, artist.CreatedOnUtc); + Assert.Equal(Optional.Some(updatedOnUtc), artist.UpdatedOnUtc); + } + + [Theory] + [InlineData(null)] // null name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void CreateWithId_WhenNameIsNullOrWhitespace_ShouldReturnArtistNameCannotBeEmptyError(string? name) + { + // Act + Result result = Artist.Create( + _artistIdFixture.Create(), + _libraryIdFixture.Create(), + name!, + Optional.None(), + Optional.None(), + [], + [_albumFixture.Create()], + DateTime.UtcNow, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void CreateWithId_WhenAlbumsListIsEmpty_ShouldReturnArtistMustHaveAtLeastOneAlbumError() + { + // Act + Result result = Artist.Create( + _artistIdFixture.Create(), + _libraryIdFixture.Create(), + "Queen", + Optional.None(), + Optional.None(), + [], + [], + DateTime.UtcNow, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + } + + [Fact] + public void AddAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldAddTheAlbumAndReturnSuccess() + { + // Arrange + Album firstAlbum = _albumFixture.Create(); + Album secondAlbum = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [firstAlbum]); + + // Act + Result result = artist.AddAlbum(secondAlbum); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, artist.Albums.Count); + Assert.Contains(secondAlbum, artist.Albums); + } + + [Fact] + public void AddAlbum_WhenAlbumIsAlreadyOwnedByTheArtist_ShouldReturnTheArtistAlreadyHasTheAlbumError() + { + // Arrange + Album album = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [album]); + + // Act + Result result = artist.AddAlbum(album); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TheArtistAlreadyHasTheAlbum, result.FirstError); + Assert.Single(artist.Albums); + } + + [Fact] + public void RemoveAlbum_WhenAlbumIsOwnedAndMoreThanOneAlbumExists_ShouldRemoveItAndReturnSuccess() + { + // Arrange + Album firstAlbum = _albumFixture.Create(); + Album secondAlbum = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [firstAlbum, secondAlbum]); + + // Act + Result result = artist.RemoveAlbum(firstAlbum); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(artist.Albums); + Assert.DoesNotContain(firstAlbum, artist.Albums); + Assert.Contains(secondAlbum, artist.Albums); + } + + [Fact] + public void RemoveAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnTheArtistDoesNotHaveTheAlbumError() + { + // Arrange + Album ownedAlbum = _albumFixture.Create(); + Album foreignAlbum = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [ownedAlbum]); + + // Act + Result result = artist.RemoveAlbum(foreignAlbum); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TheArtistDoesNotHaveTheAlbum, result.FirstError); + Assert.Single(artist.Albums); + } + + [Fact] + public void RemoveAlbum_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnArtistMustHaveAtLeastOneAlbumError() + { + // Arrange + Album onlyAlbum = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [onlyAlbum]); + + // Act + Result result = artist.RemoveAlbum(onlyAlbum); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + Assert.Single(artist.Albums); + } + + [Fact] + public void UpdateContributors_WhenCalledWithNewContributors_ShouldReplaceThemInPlace() + { + // Arrange + MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(); + MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(); + Artist artist = _artistFixture.Create(contributors: [firstContributor]); + + // Act + artist.UpdateContributors([secondContributor]); + + // Assert + MusicMediaContributor storedContributor = Assert.Single(artist.Contributors); + Assert.Equal(secondContributor, storedContributor); + Assert.DoesNotContain(firstContributor, artist.Contributors); + } + + [Fact] + public void UpdateContributors_WhenCalledWithDuplicateContributors_ShouldKeepOnlyDistinctOnes() + { + // Arrange + MusicMediaContributor contributor = _musicMediaContributorFixture.Create(); + Artist artist = _artistFixture.Create(contributors: []); + + // Act + artist.UpdateContributors([contributor, contributor]); + + // Assert + MusicMediaContributor storedContributor = Assert.Single(artist.Contributors); + Assert.Equal(contributor, storedContributor); + } + + [Fact] + public void UpdateDetails_WhenCalledWithValidData_ShouldUpdateDetailsAndSetUpdatedOnUtc() + { + // Arrange + Artist artist = _artistFixture.Create(); + MusicBrainzId musicBrainzArtistId = _musicBrainzIdFixture.Create(); + DateTime beforeUpdate = DateTime.UtcNow; + + // Act + Result result = artist.UpdateDetails( + "Queen", + Optional.Some("https://www.queenonline.com"), + Optional.Some(musicBrainzArtistId)); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Queen", artist.Name); + Assert.Equal(Optional.Some("https://www.queenonline.com"), artist.Website); + Assert.Equal(Optional.Some(musicBrainzArtistId), artist.MusicBrainzArtistId); + Assert.True(artist.UpdatedOnUtc.HasValue); + Assert.True(artist.UpdatedOnUtc.Value >= beforeUpdate); + } + + [Fact] + public void UpdateDetails_WhenNameIsNullOrWhitespace_ShouldReturnArtistNameCannotBeEmptyErrorAndNotMutate() + { + // Arrange + Artist artist = _artistFixture.Create(name: "Queen"); + string originalName = artist.Name; + Optional originalUpdatedOnUtc = artist.UpdatedOnUtc; + + // Act + Result result = artist.UpdateDetails(" ", Optional.None(), Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + Assert.Equal(originalName, artist.Name); + Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc); + } + + [Fact] + public void UpdateAlbum_WhenAlbumIsOwnedByTheArtist_ShouldUpdateItAndSetUpdatedOnUtc() + { + // Arrange + Album album = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [album]); + AlbumMetadata metadata = _albumMetadataFixture.Create(title: "A Night at the Opera"); + Optional mediaFormat = Optional.Some(MusicMediaFormat.CD); + Optional barcode = Optional.Some(_barcodeFixture.Create()); + Optional catalogNumber = Optional.Some("CAT-123456"); + Optional releaseId = Optional.Some(_musicBrainzIdFixture.Create()); + Optional releaseGroupId = Optional.Some(_musicBrainzIdFixture.Create()); + Optional releaseArtistId = Optional.Some(_musicBrainzIdFixture.Create()); + List contributors = [_musicMediaContributorFixture.Create()]; + List ratings = [_audioRatingFixture.Create()]; + DateTime beforeUpdate = DateTime.UtcNow; + + // Act + Result result = artist.UpdateAlbum( + album, + metadata, + mediaFormat, + barcode, + catalogNumber, + releaseId, + releaseGroupId, + releaseArtistId, + contributors, + ratings); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(metadata, album.Metadata); + Assert.Equal(mediaFormat, album.MediaFormat); + Assert.Equal(barcode, album.Barcode); + Assert.Equal(catalogNumber, album.CatalogNumber); + Assert.Equal(releaseId, album.MusicBrainzReleaseId); + Assert.Equal(releaseGroupId, album.MusicBrainzReleaseGroupId); + Assert.Equal(releaseArtistId, album.MusicBrainzReleaseArtistId); + Assert.Equal(contributors, album.Contributors); + Assert.Equal(ratings, album.Ratings); + Assert.True(artist.UpdatedOnUtc.HasValue); + Assert.True(artist.UpdatedOnUtc.Value >= beforeUpdate); + } + + [Fact] + public void UpdateAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundErrorAndNotMutate() + { + // Arrange + Album ownedAlbum = _albumFixture.Create(); + Album foreignAlbum = _albumFixture.Create(); + AlbumMetadata originalMetadata = foreignAlbum.Metadata; + Artist artist = _artistFixture.Create(albums: [ownedAlbum]); + Optional originalUpdatedOnUtc = artist.UpdatedOnUtc; + + // Act + Result result = artist.UpdateAlbum( + foreignAlbum, + _albumMetadataFixture.Create(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + [], + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + Assert.Equal(originalMetadata, foreignAlbum.Metadata); + Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc); + } + + [Fact] + public void UpdateTrackInAlbum_WhenAlbumAndTrackBelongToTheArtist_ShouldUpdateTheTrackAndSetUpdatedOnUtc() + { + // Arrange + Track track = _trackFixture.Create(); + Album album = _albumFixture.Create(tracks: [track]); + Artist artist = _artistFixture.Create(albums: [album]); + string path = "C:\\Music\\queen\\bohemian-rhapsody.flac"; + AudioMetadata metadata = _audioMetadataFixture.Create(); + Optional discNumber = Optional.Some(1); + Optional script = Optional.Some("Latin"); + Optional key = Optional.Some(MusicKey.BMajor); + Optional bpm = Optional.Some(72); + Optional work = Optional.Some("Bohemian Rhapsody"); + Optional recordingId = Optional.Some(_musicBrainzIdFixture.Create()); + Optional musicBrainzTrackId = Optional.Some(_musicBrainzIdFixture.Create()); + Optional workId = Optional.Some(_musicBrainzIdFixture.Create()); + List moods = [_moodFixture.Create(name: "epic")]; + List isrcs = [_isrcFixture.Create(value: "GBUM71029604")]; + List contributors = [_musicMediaContributorFixture.Create()]; + List ratings = [_audioRatingFixture.Create()]; + DateTime beforeUpdate = DateTime.UtcNow; + + // Act + Result result = artist.UpdateTrackInAlbum( + album, + track, + path, + metadata, + 11, + discNumber, + script, + key, + bpm, + work, + recordingId, + musicBrainzTrackId, + workId, + moods, + isrcs, + contributors, + ratings); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(path, track.Path); + Assert.Equal(metadata, track.Metadata); + Assert.Equal(11, track.TrackNumber); + Assert.Equal(discNumber, track.DiscNumber); + Assert.Equal(script, track.Script); + Assert.Equal(key, track.Key); + Assert.Equal(bpm, track.Bpm); + Assert.Equal(work, track.Work); + Assert.Equal(recordingId, track.MusicBrainzRecordingId); + Assert.Equal(musicBrainzTrackId, track.MusicBrainzTrackId); + Assert.Equal(workId, track.MusicBrainzWorkId); + Assert.Equal(moods, track.Moods); + Assert.Equal(isrcs, track.Isrcs); + Assert.Equal(contributors, track.Contributors); + Assert.Equal(ratings, track.Ratings); + Assert.True(artist.UpdatedOnUtc.HasValue); + Assert.True(artist.UpdatedOnUtc.Value >= beforeUpdate); + } + + [Fact] + public void UpdateTrackInAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundErrorAndNotMutate() + { + // Arrange + Album ownedAlbum = _albumFixture.Create(); + Track track = _trackFixture.Create(); + Album foreignAlbum = _albumFixture.Create(tracks: [track]); + Artist artist = _artistFixture.Create(albums: [ownedAlbum]); + string originalPath = track.Path; + Optional originalUpdatedOnUtc = artist.UpdatedOnUtc; + + // Act + Result result = artist.UpdateTrackInAlbum( + foreignAlbum, + track, + "C:\\Music\\queen\\bohemian-rhapsody.flac", + _audioMetadataFixture.Create(), + 11, + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + [], + [], + [], + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + Assert.Equal(originalPath, track.Path); + Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc); + } + + [Fact] + public void UpdateTrackInAlbum_WhenTrackIsNotInTheAlbum_ShouldReturnTrackNotFoundErrorAndNotMutate() + { + // Arrange + Track track = _trackFixture.Create(); + Album album = _albumFixture.Create(tracks: []); + Artist artist = _artistFixture.Create(albums: [album]); + string originalPath = track.Path; + Optional originalUpdatedOnUtc = artist.UpdatedOnUtc; + + // Act + Result result = artist.UpdateTrackInAlbum( + album, + track, + "C:\\Music\\queen\\bohemian-rhapsody.flac", + _audioMetadataFixture.Create(), + 11, + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + [], + [], + [], + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + Assert.Equal(originalPath, track.Path); + Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc); + } + + [Fact] + public void RemoveTrackFromAlbum_WhenAlbumAndTrackBelongToTheArtist_ShouldRemoveTheTrackAndReturnSuccess() + { + // Arrange + Track track = _trackFixture.Create(); + Album album = _albumFixture.Create(tracks: [track]); + Artist artist = _artistFixture.Create(albums: [album]); + + // Act + Result result = artist.RemoveTrackFromAlbum(album, track); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(album.Tracks); + } + + [Fact] + public void RemoveTrackFromAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + Album ownedAlbum = _albumFixture.Create(); + Track track = _trackFixture.Create(); + Album foreignAlbum = _albumFixture.Create(tracks: [track]); + Artist artist = _artistFixture.Create(albums: [ownedAlbum]); + + // Act + Result result = artist.RemoveTrackFromAlbum(foreignAlbum, track); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + Assert.Single(foreignAlbum.Tracks); + } + + [Fact] + public void RemoveTrackFromAlbum_WhenTrackIsNotInTheAlbum_ShouldReturnTrackNotFoundError() + { + // Arrange + Track track = _trackFixture.Create(); + Album album = _albumFixture.Create(tracks: []); + Artist artist = _artistFixture.Create(albums: [album]); + + // Act + Result result = artist.RemoveTrackFromAlbum(album, track); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + Assert.Empty(album.Tracks); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/ArtistIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/ArtistIdTests.cs new file mode 100644 index 00000000..55c65a3a --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/ArtistIdTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistIdTests +{ + private readonly ArtistIdFixture _artistIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + ArtistId artistId = ArtistId.CreateUnique(); + + // Assert + Assert.NotEqual(Guid.Empty, artistId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + ArtistId artistId = ArtistId.Create(value); + + // Assert + Assert.Equal(value, artistId.Value); + } + + [Fact] + public void Create_WhenCalledWithEmptyGuid_ShouldReturnIdWithEmptyValue() + { + // Act + ArtistId artistId = ArtistId.Create(Guid.Empty); + + // Assert + Assert.Equal(Guid.Empty, artistId.Value); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue() + { + // Arrange + Guid value = Guid.NewGuid(); + ArtistId artistId = _artistIdFixture.Create(value); + + // Act + string? result = artistId.ToString(); + + // Assert + Assert.Equal(value.ToString(), result); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + ArtistId firstId = _artistIdFixture.Create(value); + ArtistId secondId = _artistIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + ArtistId firstId = _artistIdFixture.Create(); + ArtistId secondId = _artistIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs new file mode 100644 index 00000000..c907b11c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs @@ -0,0 +1,241 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddArtistEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly AddArtistEndpoint _sut; + private readonly AddArtistRequestFixture _addArtistRequestFixture = new(); + private readonly ArtistResponseFixture _artistResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddArtistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithLocationAndArtistResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ArtistResponse expectedResponse = _artistResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Created createdResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, createdResult.Value); + Assert.NotNull(createdResult.Location); + Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{expectedResponse.Id}", createdResult.Location); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendAddArtistCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.Name == request.Name && + command.Website == request.Website && + command.MusicBrainzArtistId == request.MusicBrainzArtistId && + command.Contributors == request.Contributors && + command.Albums != null && + command.Albums.Count == request.Albums!.Count && + command.Albums[0].LibraryId == libraryId.ToString() && + command.Albums[0].ArtistId == null && + command.Albums[0].Metadata == request.Albums[0].Metadata && + command.Albums[0].Tracks != null && + command.Albums[0].Tracks!.Count == request.Albums[0].Tracks!.Count), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendCommandWithRawRouteValue() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullLibraryId() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.LibraryId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_artistResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs new file mode 100644 index 00000000..71a220f4 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs @@ -0,0 +1,232 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteArtistEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly DeleteArtistEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeleteArtistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Deleted, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = DomainErrors.Music.ArtistIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteArtistCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + ConfigureRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Populates the route values read by the endpoint. + /// + private void ConfigureRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs new file mode 100644 index 00000000..8b3dc592 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs @@ -0,0 +1,242 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetArtistEndpoint _sut; + private readonly ArtistResponseFixture _artistResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithArtistResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + ArtistResponse expectedResponse = _artistResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.ArtistIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetArtistQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_artistResponseFixture.Create()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs new file mode 100644 index 00000000..58f7f801 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs @@ -0,0 +1,243 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetArtistAlbumsEndpoint _sut; + private readonly AlbumResponseFixture _albumResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithAlbumResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _albumResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.ArtistIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetArtistAlbumsQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((IReadOnlyList)_albumResponseFixture.CreateMany(1))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((IReadOnlyList)_albumResponseFixture.CreateMany(1))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((IReadOnlyList)_albumResponseFixture.CreateMany(1))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From((IReadOnlyList)_albumResponseFixture.CreateMany(1)); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs new file mode 100644 index 00000000..0405a1e0 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs @@ -0,0 +1,258 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetArtistAlbumsLiteEndpoint _sut; + private readonly GetArtistAlbumsLiteRequestFixture _getArtistAlbumsLiteRequestFixture = new(); + private readonly AlbumLiteResponseFixture _albumLiteResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsLiteEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedAlbumLiteResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = CreatePaginatedResponse(albumCount: 2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetArtistAlbumsLiteQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(albumCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString() && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPaginationIsMissing_ShouldSendQueryWithNullPaginationData() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(albumCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString() && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(albumCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(albumCount: 0))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(CreatePaginatedResponse(albumCount: 0)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Creates a with the specified number of albums. + /// + /// The number of album responses to include in the data collection. + /// A configured paginated response instance. + private PaginatedResponse CreatePaginatedResponse(int albumCount) + { + List albums = []; + for (int index = 0; index < albumCount; index++) + albums.Add(_albumLiteResponseFixture.Create()); + + return _paginatedResponseFixture.Create(data: albums, currentPage: 1, perPage: 10, count: albumCount, numberOfPages: albumCount > 0 ? 1 : 0); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs new file mode 100644 index 00000000..791de963 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs @@ -0,0 +1,245 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetArtistsEndpoint _sut; + private readonly GetArtistsRequestFixture _getArtistsRequestFixture = new(); + private readonly ArtistResponseFixture _artistResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistsEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedArtistResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = CreatePaginatedResponse(artistCount: 2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetArtistsQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.SearchTerm == request.SearchTerm && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPaginationIsMissing_ShouldSendQueryWithNullPaginationData() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsRequest request = _getArtistsRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(CreatePaginatedResponse(artistCount: 0)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Creates a with the specified number of artists. + /// + /// The number of artist responses to include in the data collection. + /// A configured paginated response instance. + private PaginatedResponse CreatePaginatedResponse(int artistCount) + { + List artists = []; + for (int index = 0; index < artistCount; index++) + artists.Add(_artistResponseFixture.Create()); + + return _paginatedResponseFixture.Create(data: artists, currentPage: 1, perPage: 10, count: artistCount, numberOfPages: artistCount > 0 ? 1 : 0); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs new file mode 100644 index 00000000..538d1b45 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs @@ -0,0 +1,245 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetArtistsLiteEndpoint _sut; + private readonly GetArtistsLiteRequestFixture _getArtistsLiteRequestFixture = new(); + private readonly ArtistLiteResponseFixture _artistLiteResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistsLiteEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedArtistLiteResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = CreatePaginatedResponse(artistCount: 2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetArtistsLiteQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.SearchTerm == request.SearchTerm && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPaginationIsMissing_ShouldSendQueryWithNullPaginationData() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(CreatePaginatedResponse(artistCount: 0)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Creates a with the specified number of artists. + /// + /// The number of artist responses to include in the data collection. + /// A configured paginated response instance. + private PaginatedResponse CreatePaginatedResponse(int artistCount) + { + List artists = []; + for (int index = 0; index < artistCount; index++) + artists.Add(_artistLiteResponseFixture.Create()); + + return _paginatedResponseFixture.Create(data: artists, currentPage: 1, perPage: 10, count: artistCount, numberOfPages: artistCount > 0 ? 1 : 0); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs new file mode 100644 index 00000000..dd3599f1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs @@ -0,0 +1,263 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly UpdateArtistEndpoint _sut; + private readonly UpdateArtistRequestFixture _updateArtistRequestFixture = new(); + private readonly ArtistResponseFixture _artistResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateArtistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithArtistResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ArtistResponse expectedResponse = _artistResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.ArtistNameCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistNameCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateArtistCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString() && + command.Name == request.Name && + command.Website == request.Website && + command.MusicBrainzArtistId == request.MusicBrainzArtistId && + command.Contributors == request.Contributors && + command.Albums != null && + command.Albums.Count == request.Albums!.Count && + command.Albums[0].LibraryId == libraryId.ToString() && + command.Albums[0].ArtistId == artistId.ToString() && + command.Albums[0].AlbumId == request.Albums[0].AlbumId && + command.Albums[0].Metadata == request.Albums[0].Metadata), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_artistResponseFixture.Create()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +}